From 3b62a202d8a01b7abeb6db0a95dedf6ffcc3e2d7 Mon Sep 17 00:00:00 2001 From: mohammed naji Date: Tue, 11 Aug 2026 17:36:29 +0400 Subject: [PATCH 1/4] feat: support MCP SDK v2 protocol era --- CHANGELOG.md | 9 +- docs/library-api.md | 33 +- package-lock.json | 878 ++---------------- package.json | 11 +- scripts/build-test-fixture.mjs | 4 +- scripts/pack-verifier.mjs | 14 +- src/cli/doctor.ts | 2 +- src/cli/init.ts | 2 +- src/cli/main.ts | 10 +- src/cli/setup-native-oauth.ts | 2 +- src/config/diagnostics.ts | 2 +- src/config/schema.ts | 2 +- src/config/validate-config.ts | 2 +- src/console/console-application-service.ts | 2 +- .../console-dashboard-application-service.ts | 2 +- src/http/miftah-http-server.ts | 61 +- src/identity/identity-manager.ts | 2 +- src/index.ts | 2 +- src/mcp/server/management-tools.ts | 4 +- src/mcp/server/miftah-server.ts | 186 ++-- src/mcp/server/resource-prompt-registry.ts | 14 +- src/mcp/server/tool-registry.ts | 2 +- src/oauth/loopback-authorization-handoff.ts | 13 +- src/oauth/oauth-metadata-fetch-guard.ts | 2 +- src/oauth/remote-oauth-client-provider.ts | 71 +- .../remote-oauth-credential-refresher.ts | 9 +- src/oauth/remote-oauth-discovery.ts | 7 +- src/oauth/remote-oauth-runtime.ts | 2 +- src/runtime/create-miftah-runtime.ts | 50 +- src/setup/native-oauth-onboarding.ts | 2 +- src/setup/profile-readiness.ts | 2 +- src/upstream/contained-stdio-transport.ts | 46 +- .../multi-upstream-process-manager.ts | 2 +- src/upstream/progress-preserving-transport.ts | 3 +- src/upstream/remote-error.ts | 15 +- src/upstream/upstream-process-manager.ts | 19 +- src/upstream/upstream-session.ts | 51 +- tests/approval-fallback.test.ts | 18 +- tests/audit-outcomes.test.ts | 7 +- ...ated-request-context-docs-contract.test.ts | 6 +- tests/fixtures/fake-upstream-bundled.mjs | 90 +- tests/fixtures/fake-upstream-runtime.mjs | 41 +- tests/helpers/fake-remote-upstream.ts | 42 +- tests/http-server.test.ts | 5 +- tests/mcp-v2-migration-contract.test.ts | 28 + tests/mcp-v2-serving.test.ts | 158 ++++ tests/mcp-wrapper.test.ts | 96 +- tests/multi-upstream.test.ts | 67 +- tests/oauth-loopback-handoff.test.ts | 7 +- tests/operation-pipeline.test.ts | 3 +- tests/package-contract.test.ts | 43 +- tests/plugin-routing-server.test.ts | 3 +- ...ofile-context-handle-docs-contract.test.ts | 6 +- tests/profile-lease-pipeline.test.ts | 3 +- tests/profile-lock-mcp.test.ts | 5 +- .../profile-transition-audit-barrier.test.ts | 3 +- tests/progress-preserving-transport.test.ts | 3 +- tests/public-api.test.ts | 4 +- tests/release-config.test.ts | 18 +- tests/remote-oauth-client-provider.test.ts | 21 +- tests/remote-oauth-compatibility.test.ts | 22 +- tests/remote-oauth-runtime.test.ts | 7 +- tests/remote-oauth-transport.test.ts | 9 +- tests/remote-transport.test.ts | 410 +++++--- .../stateless-profile-context-runtime.test.ts | 9 +- tests/tool-registry.test.ts | 2 +- tsup.config.ts | 25 + 67 files changed, 1301 insertions(+), 1400 deletions(-) create mode 100644 tests/mcp-v2-migration-contract.test.ts create mode 100644 tests/mcp-v2-serving.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 92e85246..04e708d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,13 @@ All notable changes to this project will be documented in this file. The format ### Added -- [#377](https://github.com/mohanagy/miftah/issues/377) Added the opt-in production profile-context boundary for trusted modern stateless hosts. Short-lived authenticated-encrypted handles bind a named profile to the verified issuer, subject, audience, chat, deployment, and monotonic sealing-key epoch; deployment-wide revocation, exact expiry, removed-profile checks, bearer-free keyed audit correlation, audited rejection and replacement-before-revocation ordering, and fixed fail-closed errors apply on every request. Reserved tool or request metadata is stripped before audit argument capture and upstream forwarding, transition approvals are bound to the authenticated chat correlation, modern discovery enforces identical client-visible tools across profiles and is independent of prior selection calls, and existing stdio plus CLI-owned session-aware HTTP behavior remains unchanged until protocol-era negotiation is enabled separately. -- [#376](https://github.com/mohanagy/miftah/issues/376) Added a public authenticated request-context boundary for future modern stateless handling. Trusted embedding hosts can provide verified issuer, subject, audience, per-chat, issuance, and expiry claims; Miftah derives only opaque deployment-bound and separately keyed audit correlations, fails closed on missing, malformed, expired, or mismatched context, and never falls back to MCP `clientInfo`, arbitrary headers, request metadata, tool arguments, or mutable profile state. The existing CLI-owned Streamable HTTP server remains the legacy session-aware path until a supported host supplies the trusted per-chat claim and modern protocol integration is enabled. +- [#363](https://github.com/mohanagy/miftah/issues/363) Added MCP `2026-07-28` serving alongside the existing legacy initialized era. STDIO now negotiates both eras through the SDK v2 serving entry; Streamable HTTP classifies each request before routing it to a fresh request-scoped modern server or the existing bounded sessionful legacy host. Modern requests use `server/discover`, carry per-request metadata, omit `Mcp-Session-Id`, propagate cancellation to the selected upstream, and return explicit supported-version diagnostics. The new public `createMiftahServerFactory` lets a trusted embedding host attach the authenticated stateless profile-context boundary without exposing Miftah's broker, policy, audit, OAuth, routing, or lifecycle internals. +- [#377](https://github.com/mohanagy/miftah/issues/377) Added the opt-in production profile-context boundary for trusted modern stateless hosts. Short-lived authenticated-encrypted handles bind a named profile to the verified issuer, subject, audience, chat, deployment, and monotonic sealing-key epoch; deployment-wide revocation, exact expiry, removed-profile checks, bearer-free keyed audit correlation, audited rejection and replacement-before-revocation ordering, and fixed fail-closed errors apply on every request. Reserved tool or request metadata is stripped before audit argument capture and upstream forwarding, transition approvals are bound to the authenticated chat correlation, and modern discovery enforces identical client-visible tools across profiles and is independent of prior selection calls. The CLI host does not synthesize trusted chat claims; an embedding host enables the boundary through `createMiftahServerFactory`. +- [#376](https://github.com/mohanagy/miftah/issues/376) Added a public authenticated request-context boundary for modern stateless handling. Trusted embedding hosts can provide verified issuer, subject, audience, per-chat, issuance, and expiry claims; Miftah derives only opaque deployment-bound and separately keyed audit correlations, fails closed on missing, malformed, expired, or mismatched context, and never falls back to MCP `clientInfo`, arbitrary headers, request metadata, tool arguments, or mutable profile state. The CLI-owned Streamable HTTP server negotiates the modern protocol without inventing these trusted claims; embedding hosts supply them through the public server factory. + +### Changed + +- [#363](https://github.com/mohanagy/miftah/issues/363) Replaced the monolithic MCP TypeScript SDK v1 dependency with the stable v2 `client`, `core`, `node`, `server`, and legacy-server packages and migrated runtime schemas to Zod 4. Direct consumers of the old monolithic SDK deep imports must move to the corresponding split package. The CLI bundles the v2 Node adapter with patched `@hono/node-server` and Hono builds so a fresh Miftah install does not inherit the Node package's still-vulnerable 1.x adapter range; custom embedding hosts own their direct Node adapter version. Native OAuth callback completion now carries the authorization-server issuer required by the v2 provider contract; Miftah continues to validate and round-trip that issuer without exposing tokens or client secrets. ## [1.0.0] - 2026-08-11 diff --git a/docs/library-api.md b/docs/library-api.md index b4b77004..c4848514 100644 --- a/docs/library-api.md +++ b/docs/library-api.md @@ -9,6 +9,7 @@ | `MIFTAH_VERSION` | The package version compiled into Miftah's CLI and MCP metadata. | | `CURRENT_CONFIG_VERSION` | The canonical configuration format written by current Miftah presets and examples. | | `createMiftahRuntime` | Creates an MCP wrapper from a configuration file without exposing process, profile, or server internals. | +| `createMiftahServerFactory` | Creates fresh lifecycle-managed MCP server instances for the SDK v2 serving entries. | | `ProfileContextHandleService` | Mints, resolves, replaces, and revokes short-lived opaque profile selectors for a trusted modern stateless host. | | `ProfileContextHandleError` | Fixed-code error class that never includes a handle, decrypted payload, identity claim, or backend detail. | | `InMemoryProfileContextRevocationStore` | Bounded same-process implementation for tests and single-process hosts; it is not deployment-wide storage. | @@ -23,16 +24,32 @@ | `generateConfigSchema` | Generates the editor-facing JSON Schema for the configuration contract. | | `presetConfig` | Creates a supported configuration preset in memory. | -`createMiftahRuntime` returns `MiftahRuntime`, which exposes the resolved `config`, `connect(transport)`, and `close()` methods. Its optional `MiftahRuntimeOptions` enables the modern profile-context boundary described below. Supply an MCP SDK transport such as `StdioServerTransport`; transport types are provided by the direct `@modelcontextprotocol/sdk` dependency. +`createMiftahRuntime` returns `MiftahRuntime`, which exposes the resolved `config`, `connect(transport)`, and `close()` methods for hosts that own a specific transport lifecycle. `createMiftahServerFactory` is the preferred boundary for the SDK v2 serving entries because every factory invocation creates a fresh prepared Miftah server whose upstreams close with that server. Both functions accept `MiftahRuntimeOptions`, including the modern profile-context boundary described below. The removed monolithic `@modelcontextprotocol/sdk` package is not part of the supported dependency surface. Miftah's CLI bundles the v2 Node adapter with its patched Hono adapter because `@modelcontextprotocol/node@2.0.0` still advertises an unsafe 1.x adapter range; embedding hosts import and version their own `@modelcontextprotocol/node` package when adapting a custom Node HTTP server. ```ts -import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; -import { createMiftahRuntime } from "@lubab/miftah"; +import { serveStdio } from "@modelcontextprotocol/server/stdio"; +import { createMiftahServerFactory } from "@lubab/miftah"; -const runtime = await createMiftahRuntime("./miftah.json"); -await runtime.connect(new StdioServerTransport()); +const server = serveStdio(createMiftahServerFactory("./miftah.json")); + +// Later, during host shutdown: +await server.close(); ``` +For a custom HTTP host, pass the same factory to `createMcpHandler` from `@modelcontextprotocol/server` and adapt the web handler with `toNodeHandler` from `@modelcontextprotocol/node` when using Node's HTTP server. + +## MCP protocol compatibility matrix + +| Transport and era | Serving path | Lifecycle and compatibility | +| --- | --- | --- | +| STDIO, modern `2026-07-28` | CLI `miftah serve` or SDK v2 `serveStdio(createMiftahServerFactory(...))` | Negotiates with `server/discover`; there is no `initialize`/`initialized` handshake or session identifier. | +| STDIO, legacy 2025-era | The same STDIO entry | Preserves the SDK-managed `initialize`/`initialized` path. Interop tests negotiate the SDK v2 preferred legacy revision, `2025-11-25`. | +| Streamable HTTP, modern `2026-07-28` | CLI-owned `/mcp` endpoint or an embedding host's `createMcpHandler` | Creates one server per request, emits no `Mcp-Session-Id`, carries request metadata through the SDK v2 context, and propagates request cancellation upstream. | +| Streamable HTTP, legacy 2025-era | CLI-owned `/mcp` endpoint | Preserves the existing sessionful path, including `initialize`/`initialized`, `Mcp-Session-Id`, idle expiry, and bounded session admission. | +| Unsupported pinned modern revision | Modern HTTP or STDIO serving entry | Fails with a version-negotiation diagnostic containing the requested revision and the supported modern revisions; it does not silently enter the legacy path. | + +This matrix describes Miftah's tested serving boundary, not a promise that every optional feature added to any future MCP revision is implemented. The SDK v2 serving entry owns protocol-era negotiation; Miftah continues to own broker routing, policy, audit, OAuth, profile state, upstream lifecycle, and cancellation propagation. + ## Authenticated request context The additive authenticated request-context API is the trust seam for future modern stateless handling. An embedding host supplies a verifier callback that returns `VerifiedHttpRequestClaims` only after it has authenticated the request. Miftah does not parse MCP `clientInfo`, arbitrary headers, request metadata, tool arguments, or a model-generated conversation ID into this boundary. @@ -41,7 +58,7 @@ The additive authenticated request-context API is the trust seam for future mode Claims are rejected at exact expiry. Provider failures and missing claims return only `AUTH_CONTEXT_UNAVAILABLE`; malformed claims return `AUTH_CONTEXT_INVALID`. Call `requireAuthenticatedRequestContext` in a modern account-sensitive path so an absent boundary cannot silently fall back to client metadata, a mutable default, or durable active-profile state. -The current CLI-owned Streamable HTTP server remains the documented legacy session-aware path and does not synthesize these claims from its static bearer token. Until a supported host supplies a verified per-chat claim and the modern protocol path is enabled, deploy a profile-scoped or operator-locked endpoint and do not claim chat-scoped switching. +The CLI-owned Streamable HTTP server accepts both the modern request-scoped protocol path and the legacy session-aware path, but it does not synthesize verified per-chat claims from its static bearer token. Its modern requests therefore begin from configured/default profile state and do not claim authenticated chat-scoped switching. A host that needs that capability must verify its own per-chat identity claims and supply the resulting boundary through `createMiftahServerFactory(configPath, { modernProfileContext })`; otherwise deploy a profile-scoped or operator-locked endpoint. ## Stateless profile-context handles @@ -55,7 +72,7 @@ In modern mode, account-sensitive tool schemas include the reserved model-visibl A valid handle selects a profile; it is not operation authorization or idempotency. Policy, approval, identity, lease, OAuth, and upstream checks still run for every request. Missing, malformed, tampered, expired, revoked, cross-principal, cross-chat, cross-deployment, and removed-profile handles return fixed `ProfileContextHandleErrorCode` failures. The modern runtime never reads or mutates `ProfileManager`'s legacy active profile. -The package exports `ProfileContextHandleServiceOptions`, `ModernProfileContextRuntimeOptions`, `MintedProfileContext`, `ResolvedProfileContext`, `ProfileContextReplacementAudit`, `ProfileContextKeyringProvider`, `ProfileContextKeyringSnapshot`, `ProfileContextKeyEpoch`, and `ProfileContextRevocationStore` for host integration. The current CLI-owned Streamable HTTP entry point does not enable this option; protocol-era negotiation and transport selection remain separate work, so existing stdio and session-aware HTTP behavior stays unchanged. +The package exports `ProfileContextHandleServiceOptions`, `ModernProfileContextRuntimeOptions`, `MintedProfileContext`, `ResolvedProfileContext`, `ProfileContextReplacementAudit`, `ProfileContextKeyringProvider`, `ProfileContextKeyringSnapshot`, `ProfileContextKeyEpoch`, and `ProfileContextRevocationStore` for host integration. The CLI-owned Streamable HTTP entry point negotiates modern and legacy eras but does not enable trusted `modernProfileContext` claims. An embedding host can pass that option to `createMiftahServerFactory`; existing legacy session-aware behavior remains available on the same endpoint. ## Type exports @@ -83,7 +100,7 @@ The package root also exports `AuthenticatedRequestContext`, `AuthenticatedReque For identity configurations, format-dependent structural constraints, unique `requiredForRisk` tuples, and `selectionMode: "explicit" | "confirmed"` are static. A selection mode requires `requiredForRisk`. For text probes, `validateConfig` runtime-validates equality between `expected.provider` and a static `probe.provider`; JSON probes do not permit a static provider. -Programmatic diagnostics expose `ConfigDiagnostic`, `MiftahErrorCode`, and `MiftahErrorDetails`. `MiftahErrorCode` includes the stable resource-template and resource-subscription protocol error categories. The wrapper factory exposes `MiftahRuntime`. +Programmatic diagnostics expose `ConfigDiagnostic`, `MiftahErrorCode`, and `MiftahErrorDetails`. `MiftahErrorCode` includes the stable resource-template and resource-subscription protocol error categories. The wrapper factories expose `MiftahRuntime` and `createMiftahServerFactory`. ## Compatibility policy diff --git a/package-lock.json b/package-lock.json index 9fa134e3..52f4c95e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,13 @@ "version": "1.0.0", "license": "MIT", "dependencies": { - "@modelcontextprotocol/sdk": "^1.30.0", + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0", "@napi-rs/keyring": "1.3.0", "dotenv": "^17.4.2", - "zod": "^3.25.76", + "zod": "^4.2.0", "zod-to-json-schema": "3.25.2" }, "bin": { @@ -20,10 +23,13 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@hono/node-server": "2.0.10", + "@modelcontextprotocol/node": "^2.0.0", "@types/node": "^22.15.30", "@vitest/coverage-v8": "^3.2.7", "esbuild": "0.28.1", "eslint": "^10.8.0", + "hono": "4.12.34", "tsup": "^8.5.0", "typescript": "^5.8.3", "typescript-eslint": "^8.65.0", @@ -681,6 +687,7 @@ "version": "2.0.10", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.0.10.tgz", "integrity": "sha512-ZcnNVhKTmyDJeg0UlnZjvM73JBsTAuhrH/J4fjwGOw59PwOW51r4J+p6CsKZWXdKSme4MFqU62CZMOsdDrU4CA==", + "dev": true, "license": "MIT", "engines": { "node": ">=20" @@ -804,43 +811,95 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@modelcontextprotocol/sdk": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", - "integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==", + "node_modules/@modelcontextprotocol/client": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.0.0.tgz", + "integrity": "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==", "license": "MIT", "dependencies": { - "@hono/node-server": "^1.19.9 || ^2.0.5", - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1", - "content-type": "^1.0.5", - "cors": "^2.8.5", + "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", - "express": "^5.2.1", - "express-rate-limit": "^8.2.1", - "hono": "^4.11.4", "jose": "^6.1.3", - "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "license": "MIT", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/node": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.0.0.tgz", + "integrity": "sha512-Y4hAC2XdGDUdDOCbLDOCA4+aL3NUldjsOWlDL/YwpAxrPhRm1xHd7lZ+mLacvZ9t3PaH28wgNoaLQGrIk1P2pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/server": "^2.0.0", + "hono": "^4.11.4" + }, + "peerDependenciesMeta": { + "hono": { + "optional": true + } + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/server-legacy": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server-legacy/-/server-legacy-2.0.0.tgz", + "integrity": "sha512-LnffC1BSqFMHtMQxEz92lqDpHWma+ErV3ghdHDgdkCyYzVcCYKcUT5loq4kflty+Bf9C9qjJqbnphyBWyCqo8Q==", + "deprecated": "This package is a frozen copy of v1's SSE transport and OAuth Authorization Server helpers for migration purposes only. Use StreamableHTTP from @modelcontextprotocol/server and a dedicated OAuth server in production. Will not receive new features.", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.0.0", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "express-rate-limit": "^8.2.1", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", - "zod": "^3.25 || ^4.0", - "zod-to-json-schema": "^3.25.1" + "zod": "^4.2.0" }, "engines": { - "node": ">=18" + "node": ">=20" }, "peerDependencies": { - "@cfworker/json-schema": "^4.1.1", - "zod": "^3.25 || ^4.0" + "express": "^4.18.0 || ^5.0.0" }, "peerDependenciesMeta": { - "@cfworker/json-schema": { + "express": { "optional": true - }, - "zod": { - "optional": false } } }, @@ -1895,19 +1954,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "license": "MIT", - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/acorn": { "version": "8.17.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz", @@ -1931,39 +1977,6 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ajv-formats": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", - "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", - "license": "MIT", - "dependencies": { - "ajv": "^8.0.0" - }, - "peerDependencies": { - "ajv": "^8.0.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, "node_modules/any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", @@ -2003,43 +2016,6 @@ "node": "18 || 20 || >=22" } }, - "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", - "license": "MIT", - "dependencies": { - "bytes": "^3.1.2", - "content-type": "^2.0.0", - "debug": "^4.4.3", - "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", - "on-finished": "^2.4.1", - "qs": "^6.15.2", - "raw-body": "^3.0.2", - "type-is": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/body-parser/node_modules/content-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", - "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/bundle-require": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", @@ -2075,35 +2051,6 @@ "node": ">=8" } }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/chai": { "version": "5.3.3", "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", @@ -2174,19 +2121,6 @@ "node": "^14.18.0 || >=16.10.0" } }, - "node_modules/content-disposition": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", - "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/content-type": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", @@ -2196,24 +2130,6 @@ "node": ">= 0.6" } }, - "node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", - "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "license": "MIT", - "engines": { - "node": ">=6.6.0" - } - }, "node_modules/cors": { "version": "2.8.6", "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", @@ -2249,6 +2165,7 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -2300,53 +2217,6 @@ "url": "https://dotenvx.com" } }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -2354,18 +2224,6 @@ "dev": true, "license": "MIT" }, - "node_modules/es-object-atoms": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", - "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/esbuild": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", @@ -2408,12 +2266,6 @@ "@esbuild/win32-x64": "0.28.1" } }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -2616,15 +2468,6 @@ "node": ">=0.10.0" } }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/eventsource": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", @@ -2656,49 +2499,6 @@ "node": ">=12.0.0" } }, - "node_modules/express": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", - "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", - "license": "MIT", - "dependencies": { - "accepts": "^2.0.0", - "body-parser": "^2.2.1", - "content-disposition": "^1.0.0", - "content-type": "^1.0.5", - "cookie": "^0.7.1", - "cookie-signature": "^1.2.1", - "debug": "^4.4.0", - "depd": "^2.0.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "finalhandler": "^2.1.0", - "fresh": "^2.0.0", - "http-errors": "^2.0.0", - "merge-descriptors": "^2.0.0", - "mime-types": "^3.0.0", - "on-finished": "^2.4.1", - "once": "^1.4.0", - "parseurl": "^1.3.3", - "proxy-addr": "^2.0.7", - "qs": "^6.14.0", - "range-parser": "^1.2.1", - "router": "^2.2.0", - "send": "^1.1.0", - "serve-static": "^2.2.0", - "statuses": "^2.0.1", - "type-is": "^2.0.1", - "vary": "^1.1.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/express-rate-limit": { "version": "8.5.2", "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz", @@ -2721,6 +2521,7 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, "license": "MIT" }, "node_modules/fast-json-stable-stringify": { @@ -2737,22 +2538,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-uri": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", - "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -2784,27 +2569,6 @@ "node": ">=16.0.0" } }, - "node_modules/finalhandler": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", - "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "on-finished": "^2.4.1", - "parseurl": "^1.3.3", - "statuses": "^2.0.1" - }, - "engines": { - "node": ">= 18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -2855,24 +2619,6 @@ "dev": true, "license": "ISC" }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", - "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2888,52 +2634,6 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/glob": { "version": "13.0.6", "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", @@ -2965,18 +2665,6 @@ "node": ">=10.13.0" } }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -2987,34 +2675,11 @@ "node": ">=8" } }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/hono": { "version": "4.12.34", "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.34.tgz", "integrity": "sha512-GqXJqY/xJkJmuloTrnV1ZEXG3fqte+VjkUqoRNZXcrUidiUOP4fMSIHHY4tsqZBK++kVyWmt/AAfSUuy57/eSA==", + "dev": true, "license": "MIT", "engines": { "node": ">=16.9.0" @@ -3098,15 +2763,6 @@ "node": ">= 12" } }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -3130,12 +2786,6 @@ "node": ">=0.10.0" } }, - "node_modules/is-promise": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", - "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "license": "MIT" - }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -3229,18 +2879,6 @@ "dev": true, "license": "MIT" }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "license": "MIT" - }, - "node_modules/json-schema-typed": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", - "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", - "license": "BSD-2-Clause" - }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -3373,61 +3011,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/media-typer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", - "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/merge-descriptors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", - "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/mime-db": { - "version": "1.54.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", - "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", - "license": "MIT", - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/minimatch": { "version": "10.2.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", @@ -3484,6 +3067,7 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, "license": "MIT" }, "node_modules/mz": { @@ -3524,15 +3108,6 @@ "dev": true, "license": "MIT" }, - "node_modules/negotiator": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", - "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -3542,39 +3117,6 @@ "node": ">=0.10.0" } }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -3625,15 +3167,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3670,16 +3203,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/path-to-regexp": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", - "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -3830,19 +3353,6 @@ "node": ">= 0.8.0" } }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -3853,35 +3363,6 @@ "node": ">=6" } }, - "node_modules/qs": { - "version": "6.15.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", - "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", - "license": "BSD-3-Clause", - "dependencies": { - "es-define-property": "^1.0.1", - "side-channel": "^1.1.1" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", - "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/raw-body": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", @@ -3911,15 +3392,6 @@ "url": "https://paulmillr.com/funding/" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", @@ -3975,22 +3447,6 @@ "fsevents": "~2.3.2" } }, - "node_modules/router": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", - "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "depd": "^2.0.0", - "is-promise": "^4.0.0", - "parseurl": "^1.3.3", - "path-to-regexp": "^8.0.0" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -4010,51 +3466,6 @@ "node": ">=10" } }, - "node_modules/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", - "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "fresh": "^2.0.0", - "http-errors": "^2.0.1", - "mime-types": "^3.0.2", - "ms": "^2.1.3", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "statuses": "^2.0.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/serve-static": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", - "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", - "license": "MIT", - "dependencies": { - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "parseurl": "^1.3.3", - "send": "^1.2.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -4082,78 +3493,6 @@ "node": ">=8" } }, - "node_modules/side-channel": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", - "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.4", - "side-channel-list": "^1.0.1", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", - "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -4464,37 +3803,6 @@ "node": ">= 0.8.0" } }, - "node_modules/type-is": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", - "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", - "license": "MIT", - "dependencies": { - "content-type": "^2.0.0", - "media-typer": "^1.1.0", - "mime-types": "^3.0.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/type-is/node_modules/content-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", - "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -4788,12 +4096,6 @@ "node": ">=0.10.0" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", @@ -4808,9 +4110,9 @@ } }, "node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.2.0.tgz", + "integrity": "sha512-Bd5fw9wlIhtqCCxotZgdTOMwGm1a0u75wARVEY9HMs1X17trvA/lMi4+MGK5EUfYkXVTbX8UDiDKW4OgzHVUZw==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/package.json b/package.json index 6b708c3f..c9bb5c8e 100644 --- a/package.json +++ b/package.json @@ -62,18 +62,24 @@ "node": ">=20" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.30.0", + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0", "@napi-rs/keyring": "1.3.0", "dotenv": "^17.4.2", - "zod": "^3.25.76", + "zod": "^4.2.0", "zod-to-json-schema": "3.25.2" }, "devDependencies": { "@eslint/js": "^10.0.1", + "@hono/node-server": "2.0.10", + "@modelcontextprotocol/node": "^2.0.0", "@types/node": "^22.15.30", "@vitest/coverage-v8": "^3.2.7", "esbuild": "0.28.1", "eslint": "^10.8.0", + "hono": "4.12.34", "tsup": "^8.5.0", "typescript": "^5.8.3", "typescript-eslint": "^8.65.0", @@ -102,7 +108,6 @@ } }, "fast-uri": "3.1.5", - "hono": "4.12.34", "ip-address": "10.3.1", "nanoid": "3.3.17", "typescript-eslint": { diff --git a/scripts/build-test-fixture.mjs b/scripts/build-test-fixture.mjs index a2d92136..b02fab5e 100644 --- a/scripts/build-test-fixture.mjs +++ b/scripts/build-test-fixture.mjs @@ -19,7 +19,9 @@ const result = await build({ legalComments: "none", write: false }); -const bundledSource = result.outputFiles[0].text; +// esbuild preserves whitespace-only lines inside dependency template literals. +// They are behaviorally inert but fail `git diff --check` in the committed fixture. +const bundledSource = result.outputFiles[0].text.replace(/^[\t ]+$/gm, ""); if (process.argv.includes("--check")) { let currentSource; diff --git a/scripts/pack-verifier.mjs b/scripts/pack-verifier.mjs index 617e3a24..0419688d 100644 --- a/scripts/pack-verifier.mjs +++ b/scripts/pack-verifier.mjs @@ -7,6 +7,9 @@ const REQUIRED_PATHS = [ "dist/plugin-api.d.ts", "dist/plugin-api.js", "dist/plugin-host.js", + "dist/third-party/hono-node-server.LICENSE", + "dist/third-party/hono.LICENSE", + "dist/third-party/modelcontextprotocol-node.LICENSE", "dist/windows-secret-job.exe", "docs/cli.md", "docs/library-api.md", @@ -19,6 +22,11 @@ const REQUIRED_PATHS = [ ]; const ALLOWED_ROOT_PATHS = new Set(["LICENSE", "README.md", "package.json"]); +const ALLOWED_BUNDLED_LICENSE_PATHS = new Set([ + "dist/third-party/hono-node-server.LICENSE", + "dist/third-party/hono.LICENSE", + "dist/third-party/modelcontextprotocol-node.LICENSE" +]); const ALLOWED_PATH_PATTERNS = [ /^dist\/windows-secret-job\.exe$/u, /^dist\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.(?:d\.ts|d\.ts\.map|js|js\.map)$/u, @@ -46,7 +54,11 @@ function isAllowedPath(path) { if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => part === "." || part === "..")) { return false; } - return ALLOWED_ROOT_PATHS.has(path) || ALLOWED_PATH_PATTERNS.some((pattern) => pattern.test(path)); + return ( + ALLOWED_ROOT_PATHS.has(path) || + ALLOWED_BUNDLED_LICENSE_PATHS.has(path) || + ALLOWED_PATH_PATTERNS.some((pattern) => pattern.test(path)) + ); } /** diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts index 9f7dd3d7..1b4be677 100644 --- a/src/cli/doctor.ts +++ b/src/cli/doctor.ts @@ -1,7 +1,7 @@ import { access, realpath } from "node:fs/promises"; import { constants } from "node:fs"; import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path"; -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import type { Tool } from "@modelcontextprotocol/server"; import { AuditLogger } from "../audit/audit-logger.js"; import { loadConfig } from "../config/load-config.js"; import { resolvePath } from "../config/path-resolve.js"; diff --git a/src/cli/init.ts b/src/cli/init.ts index 70109f47..b164e200 100644 --- a/src/cli/init.ts +++ b/src/cli/init.ts @@ -2,7 +2,7 @@ import { mkdir } from "node:fs/promises"; import { dirname, resolve } from "node:path"; import { createInterface } from "node:readline/promises"; import type { Readable, Writable } from "node:stream"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { FetchLike } from "@modelcontextprotocol/server"; import { validateConfig } from "../config/validate-config.js"; import { buildPresetConfig, PresetCatalogError } from "../config/presets.js"; import type { GoogleSearchConsoleProfileOptions, PresetBuildOptions } from "../config/presets.js"; diff --git a/src/cli/main.ts b/src/cli/main.ts index 3bc164d9..522f958b 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -3,10 +3,10 @@ import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { loadConfig } from "../config/load-config.js"; import { generateConfigSchema } from "../config/generate-json-schema.js"; -import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { serveStdio } from "@modelcontextprotocol/server/stdio"; import { redactSecrets } from "../secrets/redact.js"; import { createRuntime } from "./create-runtime.js"; -import { createMiftahRuntime } from "../runtime/create-miftah-runtime.js"; +import { createMiftahServerFactory } from "../runtime/create-miftah-runtime.js"; import { startMiftahHttpServer } from "../http/miftah-http-server.js"; import { MIFTAH_VERSION } from "../version.js"; import { runDoctor } from "./doctor.js"; @@ -72,14 +72,12 @@ async function serve(configPath: string, transportKind = "stdio"): Promise process.once("SIGTERM", shutdown); return; } - const runtime = await createMiftahRuntime(configPath); - const transport = new StdioServerTransport(); + const server = serveStdio(createMiftahServerFactory(configPath)); const shutdown = async () => { - await runtime.close(); + await server.close(); }; process.once("SIGINT", shutdown); process.once("SIGTERM", shutdown); - await runtime.connect(transport); } function consolePort(value: string | undefined): number | undefined { diff --git a/src/cli/setup-native-oauth.ts b/src/cli/setup-native-oauth.ts index 5ca04014..cbf2b168 100644 --- a/src/cli/setup-native-oauth.ts +++ b/src/cli/setup-native-oauth.ts @@ -1,7 +1,7 @@ import { mkdir } from "node:fs/promises"; import { dirname, resolve } from "node:path"; import { createInterface } from "node:readline/promises"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { FetchLike } from "@modelcontextprotocol/server"; import { createSetupConfigurationPlan, publishSetupConfigurationPlan diff --git a/src/config/diagnostics.ts b/src/config/diagnostics.ts index 2e1e4fd9..4796d41a 100644 --- a/src/config/diagnostics.ts +++ b/src/config/diagnostics.ts @@ -1,4 +1,4 @@ -import { z } from "zod"; +import { z } from "zod/v3"; import type { MiftahErrorCode } from "../utils/errors.js"; export interface ConfigDiagnostic { diff --git a/src/config/schema.ts b/src/config/schema.ts index 1c5c4a36..84916c7c 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -1,5 +1,5 @@ import { isIP } from "node:net"; -import { z } from "zod"; +import { z } from "zod/v3"; import { canonicalizeOAuthResource } from "../oauth/canonical-resource.js"; import { parseOAuthConnectionRef, validateOAuthIssuer } from "../oauth/connection-types.js"; import { isSafeOAuthHttpsUrl } from "../oauth/url-safety.js"; diff --git a/src/config/validate-config.ts b/src/config/validate-config.ts index 6e1cdfe3..8e41a9be 100644 --- a/src/config/validate-config.ts +++ b/src/config/validate-config.ts @@ -1,4 +1,4 @@ -import type { z } from "zod"; +import type { z } from "zod/v3"; import { miftahConfigSchema, miftahPublicConfigSchema } from "./schema.js"; import type { MiftahConfig } from "./types.js"; import { diagnosticsFromZodError, formatConfigDiagnostics } from "./diagnostics.js"; diff --git a/src/console/console-application-service.ts b/src/console/console-application-service.ts index f875dc23..84614d70 100644 --- a/src/console/console-application-service.ts +++ b/src/console/console-application-service.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import { mkdir } from "node:fs/promises"; import { dirname, join } from "node:path"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { FetchLike } from "@modelcontextprotocol/server"; import { readAuditJsonl } from "../cli/audit-jsonl.js"; import { readConfigMigrationSource, type ConfigMigrationSource } from "../cli/migrate-config.js"; import { planConfigMigration } from "../config/migrate-config.js"; diff --git a/src/console/console-dashboard-application-service.ts b/src/console/console-dashboard-application-service.ts index 6db9bad8..ee2cc5c2 100644 --- a/src/console/console-dashboard-application-service.ts +++ b/src/console/console-dashboard-application-service.ts @@ -1,7 +1,7 @@ import type { ClientLauncher, ClientSelection, ClientSnippet } from "../cli/client-snippets.js"; import { realpath } from "node:fs/promises"; import { join } from "node:path"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { FetchLike } from "@modelcontextprotocol/server"; import { resolvePath } from "../config/path-resolve.js"; import { MiftahError } from "../utils/errors.js"; import { diff --git a/src/http/miftah-http-server.ts b/src/http/miftah-http-server.ts index 5b3d5040..c9014515 100644 --- a/src/http/miftah-http-server.ts +++ b/src/http/miftah-http-server.ts @@ -1,10 +1,20 @@ import { randomUUID, timingSafeEqual } from "node:crypto"; import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import { type Socket } from "node:net"; -import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { + NodeStreamableHTTPServerTransport, + toNodeHandler, + toWebRequest, + type NodeMcpRequestHandler +} from "@modelcontextprotocol/node"; +import { createMcpHandler, isLegacyRequest, type McpServerFactory } from "@modelcontextprotocol/server"; import { isCanonicalHttpHost, isLiteralLoopbackBindHost } from "../config/schema.js"; import { resolveRuntimeConfig } from "../runtime/resolve-runtime-config.js"; -import { createHttpSessionRuntime, type MiftahRuntime } from "../runtime/create-miftah-runtime.js"; +import { + createHttpRequestMiftahServerFactory, + createHttpSessionRuntime, + type MiftahRuntime +} from "../runtime/create-miftah-runtime.js"; import { MiftahError } from "../utils/errors.js"; const endpointPath = "/mcp"; @@ -31,6 +41,8 @@ export interface MiftahHttpServer { /** Internal dependency injection points for lifecycle tests and embedding hosts. */ export interface MiftahHttpServerOptions { readonly sessionRuntimeFactory?: SessionRuntimeFactory; + /** Supplies fresh request-scoped server instances for the modern protocol era. */ + readonly modernServerFactory?: McpServerFactory; /** Receives fixed, non-sensitive operator warnings only. */ readonly onWarning?: (message: string) => void; /** Receives a fixed message when asynchronous cleanup fails. */ @@ -54,7 +66,7 @@ interface SessionRecord { timer?: NodeJS.Timeout; cleanup?: Promise; readonly runtime: MiftahRuntime; - readonly transport: StreamableHTTPServerTransport; + readonly transport: NodeStreamableHTTPServerTransport; } class HttpRequestError extends Error { @@ -194,6 +206,7 @@ class HttpServerHost implements MiftahHttpServer { private readonly cleanupTasks = new Set>(); private readonly sockets = new Set(); private pendingInitializations = 0; + private modernRequests = 0; private cleanupFailed = false; private closed = false; private closePromise: Promise | undefined; @@ -204,6 +217,8 @@ class HttpServerHost implements MiftahHttpServer { private readonly configPath: string, private readonly settings: HttpServerSettings, private readonly sessionRuntimeFactory: SessionRuntimeFactory, + private readonly modernHandler: NodeMcpRequestHandler, + private readonly closeModernHandler: () => Promise, private readonly onBackgroundFailure: (message: string) => void ) { this.server.on("connection", (socket) => { @@ -242,6 +257,19 @@ class HttpServerHost implements MiftahHttpServer { } const body = request.method === "POST" ? await this.parsePostBody(request) : undefined; + const webRequest = await toWebRequest(request, body); + if (!await isLegacyRequest(webRequest, body)) { + if (this.modernRequests >= this.settings.maxSessions) { + throw new HttpRequestError(429, "Too Many Requests"); + } + this.modernRequests += 1; + try { + await this.modernHandler(request, response, body); + } finally { + this.modernRequests -= 1; + } + return; + } if (sessionId === undefined) { if (request.method !== "POST" || !isInitializeRequest(body)) throw new HttpRequestError(400, "Bad Request"); await this.initializeSession(request, response, body); @@ -314,7 +342,7 @@ class HttpServerHost implements MiftahHttpServer { } this.pendingInitializations += 1; let record: SessionRecord | undefined; - const transport = new StreamableHTTPServerTransport({ + const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: randomUUID, onsessioninitialized: (sessionId) => { if (record === undefined || record.cleanup !== undefined) return; @@ -446,6 +474,9 @@ class HttpServerHost implements MiftahHttpServer { const listener = closeListener(this.server).catch(() => { throw new Error("Miftah HTTP server shutdown failed."); }); + const modernHandler = this.closeModernHandler().catch(() => { + throw new Error("Miftah HTTP server shutdown failed."); + }); const records = [...this.sessions.values(), ...this.pendingRecords]; const results = await Promise.allSettled(records.map((record) => this.cleanupRecord(record, true))); const cleanupTaskResults = await Promise.allSettled([...this.cleanupTasks]); @@ -456,9 +487,16 @@ class HttpServerHost implements MiftahHttpServer { } catch { listenerFailed = true; } + let modernHandlerFailed = false; + try { + await modernHandler; + } catch { + modernHandlerFailed = true; + } if ( this.cleanupFailed || listenerFailed || + modernHandlerFailed || results.some((result) => result.status === "rejected") || cleanupTaskResults.some((result) => result.status === "rejected") ) { @@ -524,13 +562,26 @@ export async function startMiftahHttpServer( throw new Error("Unable to start the Miftah HTTP server."); } + const backgroundFailure = options.onBackgroundFailure ?? ((message: string) => process.stderr.write(`${message}\n`)); + const modernMcpHandler = createMcpHandler( + options.modernServerFactory ?? createHttpRequestMiftahServerFactory(configPath), + { + legacy: "reject", + onerror: () => backgroundFailure("Miftah modern MCP request failed.") + } + ); + const modernNodeHandler = toNodeHandler(modernMcpHandler, { + onerror: () => backgroundFailure("Miftah modern MCP request failed.") + }); const hostServer = new HttpServerHost( endpointUrl(settings.host, address.port), server, configPath, settings, options.sessionRuntimeFactory ?? createHttpSessionRuntime, - options.onBackgroundFailure ?? ((message) => process.stderr.write(`${message}\n`)) + modernNodeHandler, + modernMcpHandler.close, + backgroundFailure ); server.on("request", (request, response) => { void hostServer.handle(request, response); diff --git a/src/identity/identity-manager.ts b/src/identity/identity-manager.ts index c45c2122..55ca7b8f 100644 --- a/src/identity/identity-manager.ts +++ b/src/identity/identity-manager.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import type { Tool } from "@modelcontextprotocol/server"; import type { IdentityConfig, IdentityFingerprint, MiftahConfig, RiskLevel, ToolingConfig } from "../config/types.js"; import { classifyRisk } from "../policy/risk-classifier.js"; import type { UpstreamRequestOptions, UpstreamSession } from "../upstream/upstream-session.js"; diff --git a/src/index.ts b/src/index.ts index 546aa22a..65d4ce7c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,7 @@ export { MIFTAH_VERSION } from "./version.js"; export { CURRENT_CONFIG_VERSION } from "./config/versions.js"; export type { MiftahConfigVersion } from "./config/versions.js"; -export { createMiftahRuntime } from "./runtime/create-miftah-runtime.js"; +export { createMiftahRuntime, createMiftahServerFactory } from "./runtime/create-miftah-runtime.js"; export type { MiftahRuntime, MiftahRuntimeOptions } from "./runtime/create-miftah-runtime.js"; export type { ConfigDiagnostic } from "./config/diagnostics.js"; export { diff --git a/src/mcp/server/management-tools.ts b/src/mcp/server/management-tools.ts index 4817988e..5dd257b9 100644 --- a/src/mcp/server/management-tools.ts +++ b/src/mcp/server/management-tools.ts @@ -1,4 +1,4 @@ -import type { Tool, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js"; +import type { JSONValue, Tool, ToolAnnotations } from "@modelcontextprotocol/server"; export type ManagementToolInteraction = "observational" | "state-changing" | "external-probe"; export type ManagementToolAvailability = "always" | "delegated-agent"; @@ -6,7 +6,7 @@ export type ManagementToolAvailability = "always" | "delegated-agent"; export interface ManagementToolInput { readonly name: string; readonly required: boolean; - readonly schema: Readonly>; + readonly schema: JSONValue; } /** One authoritative management-tool contract for MCP, onboarding, and client guidance. */ diff --git a/src/mcp/server/miftah-server.ts b/src/mcp/server/miftah-server.ts index ac9f92fc..f1f2ea88 100644 --- a/src/mcp/server/miftah-server.ts +++ b/src/mcp/server/miftah-server.ts @@ -1,38 +1,25 @@ -import { Server } from "@modelcontextprotocol/sdk/server/index.js"; -import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js"; -import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { - CallToolRequestSchema, - ErrorCode, - GetPromptRequestSchema, - RootsListChangedNotificationSchema, - ListPromptsRequestSchema, - ListResourceTemplatesRequestSchema, - ListResourcesRequestSchema, - ListToolsRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - type CallToolResult, - type GetPromptRequest, - type GetPromptResult, - type ListPromptsRequest, - type ListPromptsResult, - type ListResourceTemplatesRequest, - type ListResourceTemplatesResult, - type ListResourcesRequest, - type ListResourcesResult, - type Prompt, - type ReadResourceResult, - type ReadResourceRequest, - type Resource, - type ResourceTemplate, - type ServerNotification, - type ServerRequest, - type SubscribeRequest, - type UnsubscribeRequest, - type Tool -} from "@modelcontextprotocol/sdk/types.js"; +import { Server, ProtocolErrorCode } from "@modelcontextprotocol/server"; +import type { + CallToolResult, + GetPromptRequest, + GetPromptResult, + ListPromptsRequest, + ListPromptsResult, + ListResourcesRequest, + ListResourcesResult, + ListResourceTemplatesRequest, + ListResourceTemplatesResult, + Prompt, + ReadResourceRequest, + ReadResourceResult, + Resource, + ResourceTemplateType, + ServerContext, + SubscribeRequest, + Tool, + Transport, + UnsubscribeRequest +} from "@modelcontextprotocol/server"; import type { MiftahConfig, ToolingConfig, UpstreamConfig } from "../../config/types.js"; import { requireAuthenticatedRequestContext, @@ -210,10 +197,7 @@ interface ProfileTransitionConfirmationBinding { readonly revision: number; } -type ProxiedRequestExtra = Pick< - RequestHandlerExtra, - "_meta" | "authInfo" | "sendNotification" | "signal" ->; +type ProxiedRequestExtra = Pick; interface ModernCallContext { readonly authenticated: AuthenticatedRequestContext; @@ -349,6 +333,9 @@ export class MiftahServer { private mcpRootsRefreshRequested = false; private mcpRootsConnection = 0; private mcpRootsInitialized = false; + private preparation?: Promise; + private startAudit?: Promise; + private closePromise?: Promise; private readonly provideRoutingContext = async (): Promise => { if (this.routingContextCollector === undefined) return emptyRoutingContext; if (!this.mcpRootsInitialized) return this.routingContextCollector(EMPTY_MCP_ROOTS); @@ -496,7 +483,7 @@ export class MiftahServer { } }); this.server.oninitialized = () => this.handleClientInitialized(); - this.server.setNotificationHandler(RootsListChangedNotificationSchema, () => { + this.server.setNotificationHandler('notifications/roots/list_changed', () => { if ( this.routingContextCollector === undefined || !this.mcpRootsInitialized || @@ -510,9 +497,30 @@ export class MiftahServer { ); }); this.registerHandlers(); + this.server.onclose = () => { + void this.close().catch(() => undefined); + }; } async connect(transport: Transport): Promise { + await this.prepare(); + await this.server.connect(transport); + await this.recordStart(); + } + + /** Prepares a fresh wrapper for an SDK-owned serving entry and returns its low-level server. */ + async prepareForServing(): Promise { + await this.prepare(); + await this.recordStart(); + return this.server; + } + + private prepare(): Promise { + this.preparation ??= this.prepareInternal(); + return this.preparation; + } + + private async prepareInternal(): Promise { await this.profileTransitions; this.profileTransitionSession += 1; this.profileTransitionConfirmations = new WeakMap(); @@ -526,18 +534,26 @@ export class MiftahServer { if (previousProfile !== activeProfile) await this.invalidateResourcePromptProfiles(previousProfile, activeProfile); this.resetMcpRoots(); await this.configureResourceSubscriptionCapability(); - await this.server.connect(transport); - await this.auditTrail.writeLifecycle({ + } + + private recordStart(): Promise { + this.startAudit ??= this.auditTrail.writeLifecycle({ operation: "wrapper/start", name: this.config.name, profile: this.profiles.current().activeProfile, lockToProfile: this.config.security?.lockToProfile ?? undefined, status: "success" }).catch(() => undefined); + return this.startAudit; } /** Closes subscriptions, the MCP server, and upstreams while preserving the first shutdown failure. */ - async close(): Promise { + close(): Promise { + this.closePromise ??= this.closeInternal(); + return this.closePromise; + } + + private async closeInternal(): Promise { this.profileTransitionSession += 1; this.profileTransitionConfirmations = new WeakMap(); let closeFailure: { readonly error: unknown } | undefined; @@ -823,7 +839,7 @@ export class MiftahServer { } let extracted: ReturnType; try { - extracted = extractProfileContext(input, extra._meta); + extracted = extractProfileContext(input, extra.mcpReq._meta); } catch (error) { throw this.normalizeProfileContextError(error); } @@ -865,7 +881,7 @@ export class MiftahServer { if (this.modernProfileContext === undefined) return this.captureStableProfileState(); let extracted: ReturnType; try { - extracted = extractProfileContext({}, extra._meta); + extracted = extractProfileContext({}, extra.mcpReq._meta); } catch (error) { throw this.normalizeProfileContextError(error); } @@ -887,7 +903,7 @@ export class MiftahServer { const runtime = this.modernProfileContext; if (runtime === undefined) throw this.profileContextError("PROFILE_CONTEXT_UNAVAILABLE"); try { - return await requireAuthenticatedRequestContext(runtime.authenticatedRequestContext, extra.authInfo); + return await requireAuthenticatedRequestContext(runtime.authenticatedRequestContext, extra.http?.authInfo); } catch (error) { throw this.normalizeProfileContextError(error); } @@ -1010,15 +1026,15 @@ export class MiftahServer { /** Registers the wrapper's MCP request handlers for the lifetime of this server instance. */ private registerHandlers(): void { - this.server.setRequestHandler(ListToolsRequestSchema, async (_request, extra) => { + this.server.setRequestHandler('tools/list', async (_request, ctx) => { const source = this.modernProfileContext === undefined ? await this.captureStableProfileState() : this.modernCatalogProfileState(); - const upstreamRequest = this.upstreamRequestContext(extra); + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "tools/list", name: "tools", sourceProfile: source.activeProfile }, async (audit) => { - if (this.modernProfileContext !== undefined) await this.authenticateModernRequest(extra); + if (this.modernProfileContext !== undefined) await this.authenticateModernRequest(ctx); const upstream = this.auditUpstreamName(); if (upstream) audit.update({ upstream }); const { profile, snapshot } = await this.runWithUpstreamRequest( @@ -1038,14 +1054,14 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { + this.server.setRequestHandler('tools/call', async (request, ctx) => { const name = request.params.name; const isManagementTool = isManagementToolName(name); const isApprovalManagementTool = name === "miftah_approve" || name === "miftah_deny"; const auditSource = this.modernProfileContext === undefined ? await this.captureStableProfileState() : this.modernCatalogProfileState(); - const upstreamRequest = this.upstreamRequestContext(extra); + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: isManagementTool ? managementOperation(name) : "tools/call", @@ -1053,7 +1069,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const prepared = await this.prepareCall(name, request.params.arguments ?? {}, extra); + const prepared = await this.prepareCall(name, request.params.arguments ?? {}, ctx); const { args, source } = prepared; audit.update({ sourceProfile: source.activeProfile, @@ -1073,7 +1089,7 @@ export class MiftahServer { args, audit, source, - { requestId: extra.requestId, signal: extra.signal }, + { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }, upstreamRequest, prepared.modern ) @@ -1083,7 +1099,7 @@ export class MiftahServer { args, audit, source, - { requestId: extra.requestId, signal: extra.signal }, + { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }, upstreamRequest ); }, @@ -1097,9 +1113,9 @@ export class MiftahServer { if (this.resourcePromptProxy.available) { const upstreamName = this.resourcePromptProxy.upstreamName; - this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async (request, extra) => { + this.server.setRequestHandler('resources/templates/list', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const upstreamRequest = this.upstreamRequestContext(extra); + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "resources/templates/list", @@ -1107,7 +1123,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const { params, source } = await this.prepareResourcePromptRequest(request.params, extra, audit); + const { params, source } = await this.prepareResourcePromptRequest(request.params, ctx, audit); audit.update({ arguments: params?.cursor === undefined ? {} : { cursor: params.cursor } }); return this.runWithUpstreamRequest(upstreamRequest, async () => { const upstream = this.resourcePromptRegistry ? undefined : this.auditUpstreamName(upstreamName); @@ -1131,10 +1147,10 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(SubscribeRequestSchema, async (request, extra) => { + this.server.setRequestHandler('resources/subscribe', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: extra.requestId, signal: extra.signal }; - const upstreamRequest = this.upstreamRequestContext(extra); + const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "resources/subscribe", @@ -1142,7 +1158,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const { params, source } = await this.prepareResourcePromptRequest(request.params, extra, audit); + const { params, source } = await this.prepareResourcePromptRequest(request.params, ctx, audit); audit.update({ name: this.redactor.redactUri(params.uri), arguments: { uri: this.redactor.redactUri(params.uri) } @@ -1159,10 +1175,10 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(UnsubscribeRequestSchema, async (request, extra) => { + this.server.setRequestHandler('resources/unsubscribe', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: extra.requestId, signal: extra.signal }; - const upstreamRequest = this.upstreamRequestContext(extra); + const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "resources/unsubscribe", @@ -1170,7 +1186,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const { params, source } = await this.prepareResourcePromptRequest(request.params, extra, audit); + const { params, source } = await this.prepareResourcePromptRequest(request.params, ctx, audit); audit.update({ name: this.redactor.redactUri(params.uri), arguments: { uri: this.redactor.redactUri(params.uri) } @@ -1187,9 +1203,9 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { + this.server.setRequestHandler('resources/list', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const upstreamRequest = this.upstreamRequestContext(extra); + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "resources/list", @@ -1197,7 +1213,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const { params, source } = await this.prepareResourcePromptRequest(request.params, extra, audit); + const { params, source } = await this.prepareResourcePromptRequest(request.params, ctx, audit); audit.update({ arguments: params?.cursor === undefined ? {} : { cursor: params.cursor } }); return this.runWithUpstreamRequest(upstreamRequest, async () => { const upstream = this.resourcePromptRegistry ? undefined : this.auditUpstreamName(upstreamName); @@ -1221,10 +1237,10 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { + this.server.setRequestHandler('resources/read', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: extra.requestId, signal: extra.signal }; - const upstreamRequest = this.upstreamRequestContext(extra); + const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "resources/read", @@ -1232,7 +1248,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const { params, source } = await this.prepareResourcePromptRequest(request.params, extra, audit); + const { params, source } = await this.prepareResourcePromptRequest(request.params, ctx, audit); audit.update({ name: this.redactor.redactUri(params.uri), arguments: { uri: this.redactor.redactUri(params.uri) } @@ -1249,9 +1265,9 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(ListPromptsRequestSchema, async (request, extra) => { + this.server.setRequestHandler('prompts/list', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const upstreamRequest = this.upstreamRequestContext(extra); + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "prompts/list", @@ -1259,7 +1275,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const { params, source } = await this.prepareResourcePromptRequest(request.params, extra, audit); + const { params, source } = await this.prepareResourcePromptRequest(request.params, ctx, audit); audit.update({ arguments: params?.cursor === undefined ? {} : { cursor: params.cursor } }); return this.runWithUpstreamRequest(upstreamRequest, async () => { const upstream = this.resourcePromptRegistry ? undefined : this.auditUpstreamName(upstreamName); @@ -1283,10 +1299,10 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { + this.server.setRequestHandler('prompts/get', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: extra.requestId, signal: extra.signal }; - const upstreamRequest = this.upstreamRequestContext(extra); + const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { operation: "prompts/get", @@ -1294,7 +1310,7 @@ export class MiftahServer { sourceProfile: auditSource.activeProfile }, async (audit) => { - const { params, source } = await this.prepareResourcePromptRequest(request.params, extra, audit); + const { params, source } = await this.prepareResourcePromptRequest(request.params, ctx, audit); audit.update({ name: params.name, arguments: { ...(params.arguments ?? {}), name: params.name } }); if (this.resourcePromptRegistry) { try { @@ -1311,11 +1327,11 @@ export class MiftahServer { } private upstreamRequestContext(extra: ProxiedRequestExtra): UpstreamRequestContext { - const progressToken = extra._meta?.progressToken; + const progressToken = extra.mcpReq._meta?.progressToken; let forwardingFailure: unknown; let pending = Promise.resolve(); const options: UpstreamRequestOptions = { - signal: extra.signal, + signal: extra.mcpReq.signal, ...(progressToken === undefined ? {} : { @@ -1323,7 +1339,7 @@ export class MiftahServer { const safeMessage = message === undefined ? undefined : this.redactor.redactText(message); pending = pending .then(() => - extra.sendNotification({ + extra.mcpReq.notify({ method: "notifications/progress", params: { progressToken, @@ -3335,7 +3351,7 @@ export class MiftahServer { function extractProfileContext( input: Record, - meta: ProxiedRequestExtra["_meta"] + meta: ProxiedRequestExtra["mcpReq"]["_meta"] ): { readonly args: Record; readonly handle?: string } { let argumentHandle: unknown; let metadataHandle: unknown; @@ -3488,7 +3504,7 @@ function isRecord(value: unknown): value is Record { } function isMethodNotFoundError(error: unknown): error is { readonly code: number } { - return isRecord(error) && error.code === ErrorCode.MethodNotFound; + return isRecord(error) && error.code === ProtocolErrorCode.MethodNotFound; } function upstreamRequestCancelled(): Error { @@ -3598,7 +3614,7 @@ function redactDirectResource(resource: Resource): Resource { }; } -function redactDirectResourceTemplate(template: ResourceTemplate): ResourceTemplate { +function redactDirectResourceTemplate(template: ResourceTemplateType): ResourceTemplateType { return { ...template, uriTemplate: redactSensitiveUri(template.uriTemplate), diff --git a/src/mcp/server/resource-prompt-registry.ts b/src/mcp/server/resource-prompt-registry.ts index d8fa531c..71b0cbd9 100644 --- a/src/mcp/server/resource-prompt-registry.ts +++ b/src/mcp/server/resource-prompt-registry.ts @@ -1,18 +1,18 @@ import { randomUUID } from "node:crypto"; -import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js"; +import { UriTemplate } from "@modelcontextprotocol/server"; import type { GetPromptResult, ListPromptsRequest, ListPromptsResult, - ListResourceTemplatesRequest, - ListResourceTemplatesResult, ListResourcesRequest, ListResourcesResult, + ListResourceTemplatesRequest, + ListResourceTemplatesResult, Prompt, ReadResourceResult, Resource, - ResourceTemplate -} from "@modelcontextprotocol/sdk/types.js"; + ResourceTemplateType +} from "@modelcontextprotocol/server"; import type { ToolDiscoveryMode } from "../../config/types.js"; import { redactUri } from "../../secrets/redact.js"; import type { UpstreamRequestOptions } from "../../upstream/upstream-session.js"; @@ -246,7 +246,7 @@ export class ResourcePromptRegistry { for (const route of routes.values()) { names.set(route.exposedName, route.exposedUriBase); } - const resourceTemplates: ResourceTemplate[] = []; + const resourceTemplates: ResourceTemplateType[] = []; for (const { upstreamName, result } of discovered) { for (const original of result.resourceTemplates) { @@ -833,7 +833,7 @@ function redactResource(resource: Resource): Resource { }; } -function redactResourceTemplate(template: ResourceTemplate): ResourceTemplate { +function redactResourceTemplate(template: ResourceTemplateType): ResourceTemplateType { return { ...template, uriTemplate: redactUri(template.uriTemplate), diff --git a/src/mcp/server/tool-registry.ts b/src/mcp/server/tool-registry.ts index 7588e0a4..cca16f7e 100644 --- a/src/mcp/server/tool-registry.ts +++ b/src/mcp/server/tool-registry.ts @@ -1,4 +1,4 @@ -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import type { Tool } from "@modelcontextprotocol/server"; import type { ToolRiskAnnotations } from "../../policy/policy-types.js"; import type { UpstreamRequestOptions } from "../../upstream/upstream-session.js"; import { MiftahError } from "../../utils/errors.js"; diff --git a/src/oauth/loopback-authorization-handoff.ts b/src/oauth/loopback-authorization-handoff.ts index 2f79a0ee..8e76fac3 100644 --- a/src/oauth/loopback-authorization-handoff.ts +++ b/src/oauth/loopback-authorization-handoff.ts @@ -5,7 +5,10 @@ import { spawn } from "node:child_process"; import { win32 } from "node:path"; import { resolveExecutablePath } from "../secrets/executable-resolver.js"; import { MiftahError } from "../utils/errors.js"; -import type { OAuthAuthorizationHandoff } from "./remote-oauth-client-provider.js"; +import type { + OAuthAuthorizationHandoff, + OAuthAuthorizationResponse +} from "./remote-oauth-client-provider.js"; const callbackPath = "/oauth/callback"; const defaultTimeoutMs = 5 * 60_000; @@ -22,7 +25,7 @@ export interface LoopbackOAuthAuthorizationHandoffOptions { interface PendingAuthorization { readonly state: string; readonly issuer: string; - readonly resolve: (code: string) => void; + readonly resolve: (response: OAuthAuthorizationResponse) => void; readonly reject: (error: MiftahError) => void; readonly timeout: ReturnType; } @@ -84,12 +87,12 @@ class LoopbackOAuthAuthorizationHandoff implements OAuthAuthorizationHandoff { authorize( authorizationUrl: URL, expected: { readonly state: string; readonly issuer: string } - ): Promise { + ): Promise { if (this.closed || this.used || this.pending !== undefined || authorizationUrl.protocol !== "https:") { return Promise.reject(authorizationFailed()); } this.used = true; - const authorization = new Promise((resolve, reject) => { + const authorization = new Promise((resolve, reject) => { const timeout = setTimeout(() => { if (this.pending?.timeout !== timeout) return; this.pending = undefined; @@ -154,7 +157,7 @@ class LoopbackOAuthAuthorizationHandoff implements OAuthAuthorizationHandoff { this.pending = undefined; clearTimeout(pending.timeout); fixedPage(response, 200, successPage); - pending.resolve(code); + pending.resolve({ authorizationCode: code, issuer }); setImmediate(() => void this.closeServer()); } diff --git a/src/oauth/oauth-metadata-fetch-guard.ts b/src/oauth/oauth-metadata-fetch-guard.ts index 90adf97e..7845758c 100644 --- a/src/oauth/oauth-metadata-fetch-guard.ts +++ b/src/oauth/oauth-metadata-fetch-guard.ts @@ -1,4 +1,4 @@ -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { FetchLike } from "@modelcontextprotocol/server"; const maximumMetadataBytes = 64 * 1_024; diff --git a/src/oauth/remote-oauth-client-provider.ts b/src/oauth/remote-oauth-client-provider.ts index 017544aa..4c18d9b6 100644 --- a/src/oauth/remote-oauth-client-provider.ts +++ b/src/oauth/remote-oauth-client-provider.ts @@ -1,12 +1,11 @@ -import { - type OAuthClientProvider, - type OAuthDiscoveryState -} from "@modelcontextprotocol/sdk/client/auth.js"; import type { + OAuthClientProvider, + OAuthDiscoveryState, OAuthClientInformationMixed, OAuthClientMetadata, - OAuthTokens -} from "@modelcontextprotocol/sdk/shared/auth.js"; + StoredOAuthClientInformation, + StoredOAuthTokens +} from "@modelcontextprotocol/client"; import { randomBytes } from "node:crypto"; import { canonicalizeOAuthResource } from "./canonical-resource.js"; import type { OAuthConnectionLifecycle } from "./connection-lifecycle.js"; @@ -18,12 +17,17 @@ import { isSafeOAuthHttpsUrl } from "./url-safety.js"; const maximumTokenLifetimeSeconds = 365 * 24 * 60 * 60; /** Browser/callback boundary used by the SDK provider without exposing authorization data. */ +export interface OAuthAuthorizationResponse { + readonly authorizationCode: string; + readonly issuer: string; +} + export interface OAuthAuthorizationHandoff { readonly redirectUrl: URL; authorize( authorizationUrl: URL, expected: { readonly state: string; readonly issuer: string } - ): Promise; + ): Promise; close(): Promise; } @@ -145,7 +149,7 @@ export function remoteOAuthClientInformation( }; } -function cloneClientInformation(value: OAuthClientInformationMixed): OAuthClientInformationMixed { +function cloneClientInformation(value: StoredOAuthClientInformation): StoredOAuthClientInformation { return structuredClone(value); } @@ -171,10 +175,10 @@ export class RemoteOAuthClientProvider implements OAuthClientProvider { private readonly registration: ClientRegistration; private readonly transactionState: string; private readonly now: () => Date; - private savedClient?: OAuthClientInformationMixed; + private savedClient?: StoredOAuthClientInformation; private savedVerifier?: string; private savedDiscovery?: OAuthDiscoveryState; - private authorization?: Promise; + private authorization?: Promise; constructor(private readonly options: RemoteOAuthClientProviderOptions) { this.registration = parseRegistration(options.binding.clientRegistration); @@ -213,19 +217,29 @@ export class RemoteOAuthClientProvider implements OAuthClientProvider { return this.transactionState; } - async clientInformation(): Promise { + async clientInformation(context?: { readonly issuer: string }): Promise { + if (context !== undefined && context.issuer !== this.options.binding.issuer) registrationUnsupported(); if (this.savedClient !== undefined) return cloneClientInformation(this.savedClient); if (this.registration.kind === "pre-registered") { - return { client_id: this.registration.clientId }; + return { client_id: this.registration.clientId, issuer: this.options.binding.issuer }; } if (this.registration.kind === "client-id-metadata") { - return { client_id: this.registration.url }; + return { client_id: this.registration.url, issuer: this.options.binding.issuer }; } return undefined; } - saveClientInformation(value: OAuthClientInformationMixed): void { - if (this.registration.kind !== "dynamic" && value.client_id !== this.clientMetadataUrl) { + saveClientInformation(value: StoredOAuthClientInformation, context?: { readonly issuer: string }): void { + const expectedClientId = this.registration.kind === "pre-registered" + ? this.registration.clientId + : this.registration.kind === "client-id-metadata" + ? this.registration.url + : undefined; + if ( + value.issuer !== this.options.binding.issuer || + (context !== undefined && context.issuer !== this.options.binding.issuer) || + (expectedClientId !== undefined && value.client_id !== expectedClientId) + ) { registrationUnsupported(); } if (typeof value.client_id !== "string" || value.client_id.length === 0 || value.client_id.length > 2_048) { @@ -234,7 +248,8 @@ export class RemoteOAuthClientProvider implements OAuthClientProvider { this.savedClient = cloneClientInformation(value); } - async tokens(): Promise { + async tokens(context?: { readonly issuer: string }): Promise { + if (context !== undefined && context.issuer !== this.options.binding.issuer) return undefined; if (this.options.forceAuthorization === true) return undefined; let credential: OAuthCredential; try { @@ -258,13 +273,20 @@ export class RemoteOAuthClientProvider implements OAuthClientProvider { return { access_token: credential.accessToken, token_type: "Bearer", + issuer: this.options.binding.issuer, ...(credential.refreshToken === undefined ? {} : { refresh_token: credential.refreshToken }), ...(expiresIn === undefined ? {} : { expires_in: expiresIn }), ...(grantedScopes.length === 0 ? {} : { scope: grantedScopes.join(" ") }) }; } - async saveTokens(tokens: OAuthTokens): Promise { + async saveTokens(tokens: StoredOAuthTokens, context?: { readonly issuer: string }): Promise { + if ( + (tokens.issuer !== undefined && tokens.issuer !== this.options.binding.issuer) || + (context !== undefined && context.issuer !== this.options.binding.issuer) + ) { + authorizationFailed(); + } if (tokens.token_type.toLowerCase() !== "bearer" || tokens.access_token.length === 0) authorizationFailed(); const grantedScopes = tokens.scope === undefined ? this.options.binding.scopes : scopes(tokens.scope); if ( @@ -333,11 +355,18 @@ export class RemoteOAuthClientProvider implements OAuthClientProvider { return this.savedVerifier; } - async waitForAuthorizationCode(): Promise { + async waitForAuthorizationResponse(): Promise { if (this.authorization === undefined) authorizationFailed(); - const code = await this.authorization; - if (typeof code !== "string" || code.length === 0 || code.length > 4_096) authorizationFailed(); - return code; + const response = await this.authorization; + if ( + typeof response.authorizationCode !== "string" || + response.authorizationCode.length === 0 || + response.authorizationCode.length > 4_096 || + response.issuer !== this.options.binding.issuer + ) { + authorizationFailed(); + } + return { ...response }; } async saveDiscoveryState(state: OAuthDiscoveryState): Promise { diff --git a/src/oauth/remote-oauth-credential-refresher.ts b/src/oauth/remote-oauth-credential-refresher.ts index 85ca7133..14470f79 100644 --- a/src/oauth/remote-oauth-credential-refresher.ts +++ b/src/oauth/remote-oauth-credential-refresher.ts @@ -1,10 +1,5 @@ -import { - discoverOAuthServerInfo, - refreshAuthorization, - type OAuthDiscoveryState -} from "@modelcontextprotocol/sdk/client/auth.js"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; -import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { discoverOAuthServerInfo, refreshAuthorization } from "@modelcontextprotocol/client"; +import type { OAuthDiscoveryState, FetchLike, OAuthTokens } from "@modelcontextprotocol/client"; import type { OAuthCredentialRefresher } from "./connection-lifecycle.js"; import type { OAuthConnectionBinding } from "./connection-types.js"; import type { OAuthCredential } from "./secure-credential-store.js"; diff --git a/src/oauth/remote-oauth-discovery.ts b/src/oauth/remote-oauth-discovery.ts index c6a78b8e..ea1f5361 100644 --- a/src/oauth/remote-oauth-discovery.ts +++ b/src/oauth/remote-oauth-discovery.ts @@ -1,8 +1,5 @@ -import { - discoverOAuthServerInfo, - type OAuthDiscoveryState -} from "@modelcontextprotocol/sdk/client/auth.js"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { discoverOAuthServerInfo } from "@modelcontextprotocol/client"; +import type { OAuthDiscoveryState, FetchLike } from "@modelcontextprotocol/client"; import { createOAuthConnectionBinding, type OAuthConnectionRef } from "./connection-types.js"; import { assertRemoteOAuthDiscovery } from "./remote-oauth-client-provider.js"; import { OAuthMetadataFetchGuard } from "./oauth-metadata-fetch-guard.js"; diff --git a/src/oauth/remote-oauth-runtime.ts b/src/oauth/remote-oauth-runtime.ts index 08a0eba8..46de0bb5 100644 --- a/src/oauth/remote-oauth-runtime.ts +++ b/src/oauth/remote-oauth-runtime.ts @@ -1,4 +1,4 @@ -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { FetchLike } from "@modelcontextprotocol/server"; import type { MiftahConfig } from "../config/types.js"; import type { SecretRedactor } from "../secrets/redact.js"; import { MiftahError } from "../utils/errors.js"; diff --git a/src/runtime/create-miftah-runtime.ts b/src/runtime/create-miftah-runtime.ts index d6d20545..3949ffc2 100644 --- a/src/runtime/create-miftah-runtime.ts +++ b/src/runtime/create-miftah-runtime.ts @@ -1,4 +1,4 @@ -import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { McpServerFactory, Transport } from "@modelcontextprotocol/server"; import { resolvePath } from "../config/path-resolve.js"; import type { MiftahConfig } from "../config/types.js"; import { MiftahServer } from "../mcp/server/miftah-server.js"; @@ -25,10 +25,10 @@ interface MiftahRuntimeFactoryOptions extends MiftahRuntimeOptions { readonly profileState?: { readonly persistActiveProfile?: false; readonly scope?: "process" | "session" }; } -async function createConfiguredMiftahRuntime( +async function createConfiguredMiftahServer( configPath: string, options: MiftahRuntimeFactoryOptions = {} -): Promise { +): Promise<{ readonly config: MiftahConfig; readonly server: MiftahServer }> { const runtimeConfigPath = resolvePath(configPath); const runtime = await createRuntime(runtimeConfigPath, undefined, { profileState: options.profileState }); const server = new MiftahServer( @@ -51,10 +51,33 @@ async function createConfiguredMiftahRuntime( options.modernProfileContext ); + return { config: runtime.config, server }; +} + +async function createConfiguredMiftahRuntime( + configPath: string, + options: MiftahRuntimeFactoryOptions = {} +): Promise { + const configured = await createConfiguredMiftahServer(configPath, options); return { - config: runtime.config, - connect: (transport) => server.connect(transport), - close: () => server.close() + config: configured.config, + connect: (transport) => configured.server.connect(transport), + close: () => configured.server.close() + }; +} + +function configuredMiftahServerFactory( + configPath: string, + options: MiftahRuntimeFactoryOptions +): McpServerFactory { + return async () => { + const configured = await createConfiguredMiftahServer(configPath, options); + try { + return await configured.server.prepareForServing(); + } catch (error) { + await configured.server.close().catch(() => undefined); + throw error; + } }; } @@ -66,6 +89,21 @@ export async function createMiftahRuntime( return createConfiguredMiftahRuntime(configPath, options); } +/** Creates fresh lifecycle-managed server instances for SDK v2 serving entries. */ +export function createMiftahServerFactory( + configPath: string, + options: MiftahRuntimeOptions = {} +): McpServerFactory { + return configuredMiftahServerFactory(configPath, options); +} + +/** Creates per-request modern HTTP servers whose mutable profile state cannot escape an exchange. */ +export function createHttpRequestMiftahServerFactory(configPath: string): McpServerFactory { + return configuredMiftahServerFactory(configPath, { + profileState: { persistActiveProfile: false, scope: "session" } + }); +} + /** Creates a fresh MCP runtime whose profile state cannot escape its HTTP client session. */ export async function createHttpSessionRuntime(configPath: string): Promise { return createConfiguredMiftahRuntime(configPath, { diff --git a/src/setup/native-oauth-onboarding.ts b/src/setup/native-oauth-onboarding.ts index 2ca93c61..96835459 100644 --- a/src/setup/native-oauth-onboarding.ts +++ b/src/setup/native-oauth-onboarding.ts @@ -1,5 +1,5 @@ import { randomUUID } from "node:crypto"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { FetchLike } from "@modelcontextprotocol/server"; import { AuditLogger } from "../audit/audit-logger.js"; import { AuditTrail } from "../audit/audit-trail.js"; import { diff --git a/src/setup/profile-readiness.ts b/src/setup/profile-readiness.ts index 8b2cfff0..3c2a56f1 100644 --- a/src/setup/profile-readiness.ts +++ b/src/setup/profile-readiness.ts @@ -1,4 +1,4 @@ -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import type { Tool } from "@modelcontextprotocol/server"; import { AuditLogger } from "../audit/audit-logger.js"; import { AuditTrail } from "../audit/audit-trail.js"; import { loadConfig } from "../config/load-config.js"; diff --git a/src/upstream/contained-stdio-transport.ts b/src/upstream/contained-stdio-transport.ts index 33cb4469..a8bd708f 100644 --- a/src/upstream/contained-stdio-transport.ts +++ b/src/upstream/contained-stdio-transport.ts @@ -1,10 +1,14 @@ import { spawn, type ChildProcess } from "node:child_process"; import process from "node:process"; import { PassThrough, type Stream } from "node:stream"; -import { getDefaultEnvironment, type StdioServerParameters } from "@modelcontextprotocol/sdk/client/stdio.js"; -import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js"; -import type { Transport, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js"; -import type { JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/sdk/types.js"; +import { + deserializeMessage, + serializeMessage, + STDIO_DEFAULT_MAX_BUFFER_SIZE +} from "@modelcontextprotocol/client"; +import type { Transport, TransportSendOptions, JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/client"; +import { getDefaultEnvironment } from "@modelcontextprotocol/client/stdio"; +import type { StdioServerParameters } from "@modelcontextprotocol/client/stdio"; import { resolveWindowsSecretCommand, spawnWindowsSecretCommand, @@ -15,6 +19,31 @@ const gracefulShutdownDelayMs = 2_000; const containmentVerificationDelayMs = 25; const containmentVerificationTimeoutMs = 1_000; +class ReportingReadBuffer { + private buffer: Buffer | undefined; + + append(chunk: Buffer): void { + if ((this.buffer?.length ?? 0) + chunk.length > STDIO_DEFAULT_MAX_BUFFER_SIZE) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${STDIO_DEFAULT_MAX_BUFFER_SIZE} bytes`); + } + this.buffer = this.buffer === undefined ? chunk : Buffer.concat([this.buffer, chunk]); + } + + readMessage(): JSONRPCMessage | null { + if (this.buffer === undefined) return null; + const lineEnd = this.buffer.indexOf("\n"); + if (lineEnd === -1) return null; + const line = this.buffer.toString("utf8", 0, lineEnd).replace(/\r$/u, ""); + this.buffer = this.buffer.subarray(lineEnd + 1); + return deserializeMessage(line); + } + + clear(): void { + this.buffer = undefined; + } +} + /** Resolves the Windows helper before Client.connect can race its child startup. */ export async function createContainedStdioClientTransport( server: StdioServerParameters @@ -45,7 +74,7 @@ export class ContainedStdioClientTransport implements Transport { onerror?: (error: Error) => void; onmessage?: (message: T, extra?: MessageExtraInfo) => void; - private readonly readBuffer = new ReadBuffer(); + private readonly readBuffer = new ReportingReadBuffer(); private readonly stderrStream: PassThrough | null; private child: ChildProcess | undefined; private containedPid: number | undefined; @@ -110,7 +139,12 @@ export class ContainedStdioClientTransport implements Transport { }); child.stdin?.on("error", (error) => this.onerror?.(error)); child.stdout?.on("data", (chunk: Buffer) => { - this.readBuffer.append(chunk); + try { + this.readBuffer.append(chunk); + } catch (error) { + this.onerror?.(asError(error)); + return; + } this.processReadBuffer(); }); child.stdout?.on("error", (error) => this.onerror?.(error)); diff --git a/src/upstream/multi-upstream-process-manager.ts b/src/upstream/multi-upstream-process-manager.ts index 3369ccdb..f00557e3 100644 --- a/src/upstream/multi-upstream-process-manager.ts +++ b/src/upstream/multi-upstream-process-manager.ts @@ -1,4 +1,4 @@ -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import type { Tool } from "@modelcontextprotocol/server"; import type { MiftahConfig, ProfileConfig, ProfileIsolationConfig } from "../config/types.js"; import { assertProfileIsolationBindings } from "../isolation/profile-runtime-isolation.js"; import { diff --git a/src/upstream/progress-preserving-transport.ts b/src/upstream/progress-preserving-transport.ts index 1f855372..639546db 100644 --- a/src/upstream/progress-preserving-transport.ts +++ b/src/upstream/progress-preserving-transport.ts @@ -1,5 +1,4 @@ -import type { Transport, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js"; -import type { JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/sdk/types.js"; +import type { Transport, TransportSendOptions, JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/server"; /** * Lets the SDK dispatch an immediately preceding progress notification before diff --git a/src/upstream/remote-error.ts b/src/upstream/remote-error.ts index b1b773cf..6de96447 100644 --- a/src/upstream/remote-error.ts +++ b/src/upstream/remote-error.ts @@ -1,8 +1,5 @@ -import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"; -import { SseError } from "@modelcontextprotocol/sdk/client/sse.js"; -import { StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { McpError } from "@modelcontextprotocol/sdk/types.js"; +import { UnauthorizedError, SseError, ProtocolError, SdkHttpError } from "@modelcontextprotocol/client"; +import type { FetchLike } from "@modelcontextprotocol/client"; import type { TransportType } from "../config/types.js"; import { MiftahError } from "../utils/errors.js"; @@ -36,11 +33,15 @@ export function asRemoteError( if (error instanceof MiftahError) return error; if (error instanceof RemoteHttpStatusError) return httpError(profile, transport, error.status); if (error instanceof UnauthorizedError) return httpError(profile, transport, 401); - if (error instanceof StreamableHTTPError || error instanceof SseError) { + if (error instanceof SdkHttpError) { + if (isHttpStatus(error.status)) return httpError(profile, transport, error.status); + return undefined; + } + if (error instanceof SseError) { if (isHttpStatus(error.code)) return httpError(profile, transport, error.code); return undefined; } - if (error instanceof McpError) { + if (error instanceof ProtocolError) { return new MiftahError( "UPSTREAM_PROTOCOL_ERROR", `UPSTREAM_PROTOCOL_ERROR: ${transport} upstream for profile '${profile}' returned MCP error ${error.code}`, diff --git a/src/upstream/upstream-process-manager.ts b/src/upstream/upstream-process-manager.ts index 745d058c..321533cd 100644 --- a/src/upstream/upstream-process-manager.ts +++ b/src/upstream/upstream-process-manager.ts @@ -1,10 +1,6 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { UnauthorizedError, type OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; -import { getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; -import type { FetchLike, Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import { getDefaultEnvironment } from "@modelcontextprotocol/client/stdio"; +import { Client, UnauthorizedError, StreamableHTTPClientTransport, SSEClientTransport } from "@modelcontextprotocol/client"; +import type { OAuthClientProvider, FetchLike, Transport, Tool } from "@modelcontextprotocol/client"; import type { Stream } from "node:stream"; import type { ProfileConfig, UpstreamConfig } from "../config/types.js"; import { expandEnvironmentReferencesWithSecretValues } from "../config/env-expand.js"; @@ -131,7 +127,10 @@ export interface UpstreamManagerOptions { /** OAuth provider capabilities the upstream manager needs to finish an interactive SDK flow. */ export interface ManagedOAuthClientProvider extends OAuthClientProvider { - waitForAuthorizationCode(): Promise; + waitForAuthorizationResponse(): Promise<{ + readonly authorizationCode: string; + readonly issuer: string; + }>; close(): Promise; } @@ -586,9 +585,9 @@ export class UpstreamProcessManager { throw oauthProvider === undefined ? error : this.oauthAuthorizationFailure(error); } try { - const authorizationCode = await oauthProvider.waitForAuthorizationCode(); + const authorization = await oauthProvider.waitForAuthorizationResponse(); await withTimeout( - streamableTransport.finishAuth(authorizationCode), + streamableTransport.finishAuth(authorization.authorizationCode, authorization.issuer), this.options.startupTimeoutMs, "OAUTH_AUTHORIZATION_FAILED", `OAUTH_AUTHORIZATION_FAILED: OAuth authorization could not be completed` diff --git a/src/upstream/upstream-session.ts b/src/upstream/upstream-session.ts index 26eb0690..579eec4b 100644 --- a/src/upstream/upstream-session.ts +++ b/src/upstream/upstream-session.ts @@ -1,26 +1,20 @@ -import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js"; -import { - PromptListChangedNotificationSchema, - ResourceListChangedNotificationSchema, - ResourceUpdatedNotificationSchema, - ToolListChangedNotificationSchema -} from "@modelcontextprotocol/sdk/types.js"; import type { CallToolRequest, CallToolResult, + Client, GetPromptRequest, - ListPromptsResult, ListPromptsRequest, - ListResourceTemplatesResult, - ListResourceTemplatesRequest, - ListResourcesResult, + ListPromptsResult, ListResourcesRequest, + ListResourcesResult, + ListResourceTemplatesRequest, + ListResourceTemplatesResult, ListToolsResult, ReadResourceRequest, + RequestOptions, SubscribeRequest, UnsubscribeRequest -} from "@modelcontextprotocol/sdk/types.js"; +} from "@modelcontextprotocol/client"; import { MiftahError } from "../utils/errors.js"; /** Lets the process manager bracket upstream work so idle shutdown cannot interrupt an active request. */ @@ -50,16 +44,16 @@ export class UpstreamSession { private readonly activity?: UpstreamSessionActivity, private readonly mapRequestError?: UpstreamRequestErrorMapper ) { - this.client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + this.client.setNotificationHandler("notifications/resources/updated", (notification) => { this.notifyResourceUpdated(notification.params.uri); }); - this.client.setNotificationHandler(ResourceListChangedNotificationSchema, () => { + this.client.setNotificationHandler("notifications/resources/list_changed", () => { this.notifyListChanged("resources"); }); - this.client.setNotificationHandler(PromptListChangedNotificationSchema, () => { + this.client.setNotificationHandler("notifications/prompts/list_changed", () => { this.notifyListChanged("prompts"); }); - this.client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + this.client.setNotificationHandler("notifications/tools/list_changed", () => { this.notifyListChanged("tools"); }); } @@ -90,25 +84,35 @@ export class UpstreamSession { } listTools(options?: UpstreamRequestOptions): Promise { - return this.request((requestOptions) => this.client.listTools(undefined, requestOptions), options); + return this.request( + (requestOptions) => this.client.request({ method: "tools/list", params: {} }, requestOptions), + options + ); } callTool(params: CallToolRequest["params"], options?: UpstreamRequestOptions): Promise { return this.request( - (requestOptions) => this.client.callTool(params, undefined, requestOptions) as Promise, + (requestOptions) => this.client.callTool(params, requestOptions) as Promise, options ); } listResources(params?: ListResourcesRequest["params"], options?: UpstreamRequestOptions): Promise { - return this.request((requestOptions) => this.client.listResources(params, requestOptions), options); + return this.request( + (requestOptions) => this.client.request({ method: "resources/list", params: params ?? {} }, requestOptions), + options + ); } listResourceTemplates( params?: ListResourceTemplatesRequest["params"], options?: UpstreamRequestOptions ): Promise { - return this.request((requestOptions) => this.client.listResourceTemplates(params, requestOptions), options); + return this.request( + (requestOptions) => + this.client.request({ method: "resources/templates/list", params: params ?? {} }, requestOptions), + options + ); } readResource(params: ReadResourceRequest["params"], options?: UpstreamRequestOptions) { @@ -124,7 +128,10 @@ export class UpstreamSession { } listPrompts(params?: ListPromptsRequest["params"], options?: UpstreamRequestOptions): Promise { - return this.request((requestOptions) => this.client.listPrompts(params, requestOptions), options); + return this.request( + (requestOptions) => this.client.request({ method: "prompts/list", params: params ?? {} }, requestOptions), + options + ); } getPrompt(params: GetPromptRequest["params"], options?: UpstreamRequestOptions) { diff --git a/tests/approval-fallback.test.ts b/tests/approval-fallback.test.ts index c0344886..5fa38578 100644 --- a/tests/approval-fallback.test.ts +++ b/tests/approval-fallback.test.ts @@ -1,6 +1,4 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import { ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { access, mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -331,7 +329,7 @@ describe("approval fallback", () => { { capabilities: { elicitation: { form: {} } } } ); const elicitationRequests: unknown[] = []; - client.setRequestHandler(ElicitRequestSchema, async (request) => { + client.setRequestHandler('elicitation/create', async (request) => { elicitationRequests.push(request); return { action: "accept", content: { approved: true } }; }); @@ -378,7 +376,7 @@ describe("approval fallback", () => { { name: "profile-switch-decline-client", version: "1.0.0" }, { capabilities: { elicitation: { form: {} } } } ); - client.setRequestHandler(ElicitRequestSchema, async () => ({ action: "accept", content: { approved: false } })); + client.setRequestHandler('elicitation/create', async () => ({ action: "accept", content: { approved: false } })); try { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); @@ -421,7 +419,7 @@ describe("approval fallback", () => { formOpened = resolve; }); let acceptForm: (() => void) | undefined; - client.setRequestHandler(ElicitRequestSchema, async () => { + client.setRequestHandler('elicitation/create', async () => { formOpened(); return new Promise((resolve) => { acceptForm = () => resolve({ action: "accept", content: { approved: true } }); @@ -1114,7 +1112,7 @@ describe("approval fallback", () => { { capabilities: { elicitation: { form: {} } } } ); let elicitationRequest: unknown; - client.setRequestHandler(ElicitRequestSchema, async (request) => { + client.setRequestHandler('elicitation/create', async (request) => { elicitationRequest = request; return { action: "accept", content: { approved: true } }; }); @@ -1169,7 +1167,7 @@ describe("approval fallback", () => { { name: "approval-elicit-expiry-client", version: "1.0.0" }, { capabilities: { elicitation: { form: {} } } } ); - client.setRequestHandler(ElicitRequestSchema, async () => { + client.setRequestHandler('elicitation/create', async () => { now = new Date("2026-07-12T00:00:01.000Z"); return { action: "accept", content: { approved: true } }; }); @@ -1214,7 +1212,7 @@ describe("approval fallback", () => { { capabilities: { elicitation: { form: {} } } } ); const elicitationRequests: unknown[] = []; - client.setRequestHandler(ElicitRequestSchema, async (request) => { + client.setRequestHandler('elicitation/create', async (request) => { elicitationRequests.push(request); return { action: "accept", content: { approved: true } }; }); @@ -1260,7 +1258,7 @@ describe("approval fallback", () => { { name: "approval-decline-client", version: "1.0.0" }, { capabilities: { elicitation: { form: {} } } } ); - client.setRequestHandler(ElicitRequestSchema, async () => ({ action: "accept", content: { approved: false } })); + client.setRequestHandler('elicitation/create', async () => ({ action: "accept", content: { approved: false } })); try { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); diff --git a/tests/audit-outcomes.test.ts b/tests/audit-outcomes.test.ts index 18474a4f..e6c89b4b 100644 --- a/tests/audit-outcomes.test.ts +++ b/tests/audit-outcomes.test.ts @@ -1,6 +1,5 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; +import { CallToolResultSchema } from "@modelcontextprotocol/core"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { mkdtemp, readFile, rm, unlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -348,7 +347,7 @@ describe("audit outcomes", () => { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); const health = CallToolResultSchema.parse( - await client.callTool({ name: "miftah_health", arguments: {} }, CallToolResultSchema) + await client.callTool({ name: "miftah_health", arguments: {} }) ); const content = health.content[0]; if (content?.type !== "text") throw new Error("Expected a text health result"); diff --git a/tests/authenticated-request-context-docs-contract.test.ts b/tests/authenticated-request-context-docs-contract.test.ts index 33072d01..844b412f 100644 --- a/tests/authenticated-request-context-docs-contract.test.ts +++ b/tests/authenticated-request-context-docs-contract.test.ts @@ -14,7 +14,8 @@ describe("authenticated request-context documentation contract", () => { expect(documentation).toContain("does not parse MCP `clientInfo`, arbitrary headers"); expect(documentation).toContain("profile-scoped or operator-locked endpoint"); expect(documentation).toContain("it is not an authorization credential"); - expect(documentation).toContain("remains the documented legacy session-aware path"); + expect(documentation).toContain("accepts both the modern request-scoped protocol path and the legacy session-aware path"); + expect(documentation).toContain("does not synthesize verified per-chat claims"); }); it("records the additive security boundary under the next release", async () => { @@ -23,7 +24,8 @@ describe("authenticated request-context documentation contract", () => { const unreleased = afterUnreleased.split(/^## \[/mu, 1)[0] ?? ""; expect(unreleased).toContain("[#376]"); - expect(unreleased).toContain("future modern stateless handling"); + expect(unreleased).toContain("for modern stateless handling"); expect(unreleased).toContain("never falls back to MCP `clientInfo`"); + expect(unreleased).toContain("embedding hosts supply them through the public server factory"); }); }); diff --git a/tests/fixtures/fake-upstream-bundled.mjs b/tests/fixtures/fake-upstream-bundled.mjs index 3b9d110b..209a7229 100644 --- a/tests/fixtures/fake-upstream-bundled.mjs +++ b/tests/fixtures/fake-upstream-bundled.mjs @@ -1,50 +1,46 @@ -var dh=Object.create;var Dn=Object.defineProperty;var fh=Object.getOwnPropertyDescriptor;var mh=Object.getOwnPropertyNames;var hh=Object.getPrototypeOf,_h=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},ic=(t,e)=>{for(var r in e)Dn(t,r,{get:e[r],enumerable:!0})},gh=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of mh(e))!_h.call(t,n)&&n!==r&&Dn(t,n,{get:()=>e[n],enumerable:!(o=fh(e,n))||o.enumerable});return t};var ac=(t,e,r)=>(r=t!=null?dh(hh(t)):{},gh(e||!t||!t.__esModule?Dn(r,"default",{value:t,enumerable:!0}):r,t));var Pr=S(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.regexpCode=q.getEsmExportName=q.getProperty=q.safeStringify=q.stringify=q.strConcat=q.addCodeArg=q.str=q._=q.nil=q._Code=q.Name=q.IDENTIFIER=q._CodeOrName=void 0;var Er=class{};q._CodeOrName=Er;q.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var gt=class extends Er{constructor(e){if(super(),!q.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};q.Name=gt;var Ie=class extends Er{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,o)=>`${r}${o}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,o)=>(o instanceof gt&&(r[o.str]=(r[o.str]||0)+1),r),{})}};q._Code=Ie;q.nil=new Ie("");function Pp(t,...e){let r=[t[0]],o=0;for(;o{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ValueScope=Te.ValueScopeName=Te.Scope=Te.varKinds=Te.UsedValueState=void 0;var be=Pr(),ti=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Zo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Zo||(Te.UsedValueState=Zo={}));Te.varKinds={const:new be.Name("const"),let:new be.Name("let"),var:new be.Name("var")};var Do=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof be.Name?e:this.name(e)}name(e){return new be.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,o;if(!((o=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||o===void 0)&&o.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Te.Scope=Do;var Mo=class extends be.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:o}){this.value=e,this.scopePath=(0,be._)`.${new be.Name(r)}[${o}]`}};Te.ValueScopeName=Mo;var zy=(0,be._)`\n`,ri=class extends Do{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?zy:be.nil}}get(){return this._scope}name(e){return new Mo(e,this._newName(e))}value(e,r){var o;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let n=this.toName(e),{prefix:s}=n,i=(o=r.key)!==null&&o!==void 0?o:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,n);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,n.setValue(r,{property:s,itemIndex:l}),n}getValue(e,r){let o=this._values[e];if(o)return o.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,o=>{if(o.scopePath===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return(0,be._)`${e}${o.scopePath}`})}scopeCode(e=this._values,r,o){return this._reduceValues(e,n=>{if(n.value===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return n.value.code},r,o)}_reduceValues(e,r,o={},n){let s=be.nil;for(let i in e){let a=e[i];if(!a)continue;let c=o[i]=o[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Zo.Started);let u=r(l);if(u){let p=this.opts.es5?Te.varKinds.var:Te.varKinds.const;s=(0,be._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=n?.(l))s=(0,be._)`${s}${u}${this.opts._n}`;else throw new ti(l);c.set(l,Zo.Completed)})}return s}};Te.ValueScope=ri});var O=S(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.or=N.and=N.not=N.CodeGen=N.operators=N.varKinds=N.ValueScopeName=N.ValueScope=N.Scope=N.Name=N.regexpCode=N.stringify=N.getProperty=N.nil=N.strConcat=N.str=N._=void 0;var Z=Pr(),je=oi(),it=Pr();Object.defineProperty(N,"_",{enumerable:!0,get:function(){return it._}});Object.defineProperty(N,"str",{enumerable:!0,get:function(){return it.str}});Object.defineProperty(N,"strConcat",{enumerable:!0,get:function(){return it.strConcat}});Object.defineProperty(N,"nil",{enumerable:!0,get:function(){return it.nil}});Object.defineProperty(N,"getProperty",{enumerable:!0,get:function(){return it.getProperty}});Object.defineProperty(N,"stringify",{enumerable:!0,get:function(){return it.stringify}});Object.defineProperty(N,"regexpCode",{enumerable:!0,get:function(){return it.regexpCode}});Object.defineProperty(N,"Name",{enumerable:!0,get:function(){return it.Name}});var Fo=oi();Object.defineProperty(N,"Scope",{enumerable:!0,get:function(){return Fo.Scope}});Object.defineProperty(N,"ValueScope",{enumerable:!0,get:function(){return Fo.ValueScope}});Object.defineProperty(N,"ValueScopeName",{enumerable:!0,get:function(){return Fo.ValueScopeName}});Object.defineProperty(N,"varKinds",{enumerable:!0,get:function(){return Fo.varKinds}});N.operators={GT:new Z._Code(">"),GTE:new Z._Code(">="),LT:new Z._Code("<"),LTE:new Z._Code("<="),EQ:new Z._Code("==="),NEQ:new Z._Code("!=="),NOT:new Z._Code("!"),OR:new Z._Code("||"),AND:new Z._Code("&&"),ADD:new Z._Code("+")};var Xe=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ni=class extends Xe{constructor(e,r,o){super(),this.varKind=e,this.name=r,this.rhs=o}render({es5:e,_n:r}){let o=e?je.varKinds.var:this.varKind,n=this.rhs===void 0?"":` = ${this.rhs}`;return`${o} ${this.name}${n};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Dt(this.rhs,e,r)),this}get names(){return this.rhs instanceof Z._CodeOrName?this.rhs.names:{}}},qo=class extends Xe{constructor(e,r,o){super(),this.lhs=e,this.rhs=r,this.sideEffects=o}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Z.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Dt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Z.Name?{}:{...this.lhs.names};return Uo(e,this.rhs)}},si=class extends qo{constructor(e,r,o,n){super(e,o,n),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ii=class extends Xe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ai=class extends Xe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ci=class extends Xe{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ui=class extends Xe{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Dt(this.code,e,r),this}get names(){return this.code instanceof Z._CodeOrName?this.code.names:{}}},Rr=class extends Xe{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,o)=>r+o.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let o=e[r].optimizeNodes();Array.isArray(o)?e.splice(r,1,...o):o?e[r]=o:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:o}=this,n=o.length;for(;n--;){let s=o[n];s.optimizeNames(e,r)||(Ey(e,s.names),o.splice(n,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>$t(e,r.names),{})}},Qe=class extends Rr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},li=class extends Rr{},Zt=class extends Qe{};Zt.kind="else";var yt=class t extends Qe{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let o=r.optimizeNodes();r=this.else=Array.isArray(o)?new Zt(o):o}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ip(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var o;if(this.else=(o=this.else)===null||o===void 0?void 0:o.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Dt(this.condition,e,r),this}get names(){let e=super.names;return Uo(e,this.condition),this.else&&$t(e,this.else.names),e}};yt.kind="if";var vt=class extends Qe{};vt.kind="for";var pi=class extends vt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Dt(this.iteration,e,r),this}get names(){return $t(super.names,this.iteration.names)}},di=class extends vt{constructor(e,r,o,n){super(),this.varKind=e,this.name=r,this.from=o,this.to=n}render(e){let r=e.es5?je.varKinds.var:this.varKind,{name:o,from:n,to:s}=this;return`for(${r} ${o}=${n}; ${o}<${s}; ${o}++)`+super.render(e)}get names(){let e=Uo(super.names,this.from);return Uo(e,this.to)}},Lo=class extends vt{constructor(e,r,o,n){super(),this.loop=e,this.varKind=r,this.name=o,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Dt(this.iterable,e,r),this}get names(){return $t(super.names,this.iterable.names)}},Ir=class extends Qe{constructor(e,r,o){super(),this.name=e,this.args=r,this.async=o}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ir.kind="func";var Or=class extends Rr{render(e){return"return "+super.render(e)}};Or.kind="return";var fi=class extends Qe{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var o,n;return super.optimizeNames(e,r),(o=this.catch)===null||o===void 0||o.optimizeNames(e,r),(n=this.finally)===null||n===void 0||n.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&$t(e,this.catch.names),this.finally&&$t(e,this.finally.names),e}},Nr=class extends Qe{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Nr.kind="catch";var Ar=class extends Qe{render(e){return"finally"+super.render(e)}};Ar.kind="finally";var mi=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?` -`:""},this._extScope=e,this._scope=new je.Scope({parent:e}),this._nodes=[new li]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let o=this._extScope.value(e,r);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,o,n){let s=this._scope.toName(r);return o!==void 0&&n&&(this._constants[s.str]=o),this._leafNode(new ni(e,s,o)),s}const(e,r,o){return this._def(je.varKinds.const,e,r,o)}let(e,r,o){return this._def(je.varKinds.let,e,r,o)}var(e,r,o){return this._def(je.varKinds.var,e,r,o)}assign(e,r,o){return this._leafNode(new qo(e,r,o))}add(e,r){return this._leafNode(new si(e,N.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Z.nil&&this._leafNode(new ui(e)),this}object(...e){let r=["{"];for(let[o,n]of e)r.length>1&&r.push(","),r.push(o),(o!==n||this.opts.es5)&&(r.push(":"),(0,Z.addCodeArg)(r,n));return r.push("}"),new Z._Code(r)}if(e,r,o){if(this._blockNode(new yt(e)),r&&o)this.code(r).else().code(o).endIf();else if(r)this.code(r).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new yt(e))}else(){return this._elseNode(new Zt)}endIf(){return this._endBlockNode(yt,Zt)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new pi(e),r)}forRange(e,r,o,n,s=this.opts.es5?je.varKinds.var:je.varKinds.let){let i=this._scope.toName(e);return this._for(new di(s,i,r,o),()=>n(i))}forOf(e,r,o,n=je.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof Z.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Z._)`${i}.length`,a=>{this.var(s,(0,Z._)`${i}[${a}]`),o(s)})}return this._for(new Lo("of",n,s,r),()=>o(s))}forIn(e,r,o,n=this.opts.es5?je.varKinds.var:je.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Z._)`Object.keys(${r})`,o);let s=this._scope.toName(e);return this._for(new Lo("in",n,s,r),()=>o(s))}endFor(){return this._endBlockNode(vt)}label(e){return this._leafNode(new ii(e))}break(e){return this._leafNode(new ai(e))}return(e){let r=new Or;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Or)}try(e,r,o){if(!r&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let n=new fi;if(this._blockNode(n),this.code(e),r){let s=this.name("e");this._currNode=n.catch=new Nr(s),r(s)}return o&&(this._currNode=n.finally=new Ar,this.code(o)),this._endBlockNode(Nr,Ar)}throw(e){return this._leafNode(new ci(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-r;if(o<0||e!==void 0&&o!==e)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Z.nil,o,n){return this._blockNode(new Ir(e,r,o)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(Ir)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let o=this._currNode;if(o instanceof e||r&&o instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof yt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};N.CodeGen=mi;function $t(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Uo(t,e){return e instanceof Z._CodeOrName?$t(t,e.names):t}function Dt(t,e,r){if(t instanceof Z.Name)return o(t);if(!n(t))return t;return new Z._Code(t._items.reduce((s,i)=>(i instanceof Z.Name&&(i=o(i)),i instanceof Z._Code?s.push(...i._items):s.push(i),s),[]));function o(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function n(s){return s instanceof Z._Code&&s._items.some(i=>i instanceof Z.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Ey(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ip(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Z._)`!${hi(t)}`}N.not=Ip;var ky=Op(N.operators.AND);function Py(...t){return t.reduce(ky)}N.and=Py;var Ry=Op(N.operators.OR);function Iy(...t){return t.reduce(Ry)}N.or=Iy;function Op(t){return(e,r)=>e===Z.nil?r:r===Z.nil?e:(0,Z._)`${hi(e)} ${t} ${hi(r)}`}function hi(t){return t instanceof Z.Name?t:(0,Z._)`(${t})`}});var D=S(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.checkStrictMode=A.getErrorPath=A.Type=A.useFunc=A.setEvaluated=A.evaluatedPropsToName=A.mergeEvaluated=A.eachItem=A.unescapeJsonPointer=A.escapeJsonPointer=A.escapeFragment=A.unescapeFragment=A.schemaRefOrVal=A.schemaHasRulesButRef=A.schemaHasRules=A.checkUnknownRules=A.alwaysValidSchema=A.toHash=void 0;var V=O(),Oy=Pr();function Ny(t){let e={};for(let r of t)e[r]=!0;return e}A.toHash=Ny;function Ay(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Cp(t,e),!jp(e,t.self.RULES.all))}A.alwaysValidSchema=Ay;function Cp(t,e=t.schema){let{opts:r,self:o}=t;if(!r.strictSchema||typeof e=="boolean")return;let n=o.RULES.keywords;for(let s in e)n[s]||Mp(t,`unknown keyword: "${s}"`)}A.checkUnknownRules=Cp;function jp(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}A.schemaHasRules=jp;function Cy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}A.schemaHasRulesButRef=Cy;function jy({topSchemaRef:t,schemaPath:e},r,o,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,V._)`${r}`}return(0,V._)`${t}${e}${(0,V.getProperty)(o)}`}A.schemaRefOrVal=jy;function Zy(t){return Zp(decodeURIComponent(t))}A.unescapeFragment=Zy;function Dy(t){return encodeURIComponent(gi(t))}A.escapeFragment=Dy;function gi(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}A.escapeJsonPointer=gi;function Zp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}A.unescapeJsonPointer=Zp;function My(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}A.eachItem=My;function Np({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:o}){return(n,s,i,a)=>{let c=i===void 0?s:i instanceof V.Name?(s instanceof V.Name?t(n,s,i):e(n,s,i),i):s instanceof V.Name?(e(n,i,s),s):r(s,i);return a===V.Name&&!(c instanceof V.Name)?o(n,c):c}}A.mergeEvaluated={props:Np({mergeNames:(t,e,r)=>t.if((0,V._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,V._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,V._)`${r} || {}`).code((0,V._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,V._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,V._)`${r} || {}`),yi(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Dp}),items:Np({mergeNames:(t,e,r)=>t.if((0,V._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,V._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,V._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,V._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Dp(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,V._)`{}`);return e!==void 0&&yi(t,r,e),r}A.evaluatedPropsToName=Dp;function yi(t,e,r){Object.keys(r).forEach(o=>t.assign((0,V._)`${e}${(0,V.getProperty)(o)}`,!0))}A.setEvaluated=yi;var Ap={};function qy(t,e){return t.scopeValue("func",{ref:e,code:Ap[e.code]||(Ap[e.code]=new Oy._Code(e.code))})}A.useFunc=qy;var _i;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_i||(A.Type=_i={}));function Ly(t,e,r){if(t instanceof V.Name){let o=e===_i.Num;return r?o?(0,V._)`"[" + ${t} + "]"`:(0,V._)`"['" + ${t} + "']"`:o?(0,V._)`"/" + ${t}`:(0,V._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,V.getProperty)(t).toString():"/"+gi(t)}A.getErrorPath=Ly;function Mp(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}A.checkStrictMode=Mp});var et=S(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var me=O(),Uy={data:new me.Name("data"),valCxt:new me.Name("valCxt"),instancePath:new me.Name("instancePath"),parentData:new me.Name("parentData"),parentDataProperty:new me.Name("parentDataProperty"),rootData:new me.Name("rootData"),dynamicAnchors:new me.Name("dynamicAnchors"),vErrors:new me.Name("vErrors"),errors:new me.Name("errors"),this:new me.Name("this"),self:new me.Name("self"),scope:new me.Name("scope"),json:new me.Name("json"),jsonPos:new me.Name("jsonPos"),jsonLen:new me.Name("jsonLen"),jsonPart:new me.Name("jsonPart")};vi.default=Uy});var Cr=S(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.extendErrors=he.resetErrorsCount=he.reportExtraError=he.reportError=he.keyword$DataError=he.keywordError=void 0;var M=O(),Vo=D(),ve=et();he.keywordError={message:({keyword:t})=>(0,M.str)`must pass "${t}" keyword validation`};he.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,M.str)`"${t}" keyword must be ${e} ($data)`:(0,M.str)`"${t}" keyword is invalid ($data)`};function Fy(t,e=he.keywordError,r,o){let{it:n}=t,{gen:s,compositeRule:i,allErrors:a}=n,c=Up(t,e,r);o??(i||a)?qp(s,c):Lp(n,(0,M._)`[${c}]`)}he.reportError=Fy;function Vy(t,e=he.keywordError,r){let{it:o}=t,{gen:n,compositeRule:s,allErrors:i}=o,a=Up(t,e,r);qp(n,a),s||i||Lp(o,ve.default.vErrors)}he.reportExtraError=Vy;function Hy(t,e){t.assign(ve.default.errors,e),t.if((0,M._)`${ve.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,M._)`${ve.default.vErrors}.length`,e),()=>t.assign(ve.default.vErrors,null)))}he.resetErrorsCount=Hy;function Ky({gen:t,keyword:e,schemaValue:r,data:o,errsCount:n,it:s}){if(n===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",n,ve.default.errors,a=>{t.const(i,(0,M._)`${ve.default.vErrors}[${a}]`),t.if((0,M._)`${i}.instancePath === undefined`,()=>t.assign((0,M._)`${i}.instancePath`,(0,M.strConcat)(ve.default.instancePath,s.errorPath))),t.assign((0,M._)`${i}.schemaPath`,(0,M.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,M._)`${i}.schema`,r),t.assign((0,M._)`${i}.data`,o))})}he.extendErrors=Ky;function qp(t,e){let r=t.const("err",e);t.if((0,M._)`${ve.default.vErrors} === null`,()=>t.assign(ve.default.vErrors,(0,M._)`[${r}]`),(0,M._)`${ve.default.vErrors}.push(${r})`),t.code((0,M._)`${ve.default.errors}++`)}function Lp(t,e){let{gen:r,validateName:o,schemaEnv:n}=t;n.$async?r.throw((0,M._)`new ${t.ValidationError}(${e})`):(r.assign((0,M._)`${o}.errors`,e),r.return(!1))}var St={keyword:new M.Name("keyword"),schemaPath:new M.Name("schemaPath"),params:new M.Name("params"),propertyName:new M.Name("propertyName"),message:new M.Name("message"),schema:new M.Name("schema"),parentSchema:new M.Name("parentSchema")};function Up(t,e,r){let{createErrors:o}=t.it;return o===!1?(0,M._)`{}`:Gy(t,e,r)}function Gy(t,e,r={}){let{gen:o,it:n}=t,s=[By(n,r),Jy(t,r)];return Wy(t,e,s),o.object(...s)}function By({errorPath:t},{instancePath:e}){let r=e?(0,M.str)`${t}${(0,Vo.getErrorPath)(e,Vo.Type.Str)}`:t;return[ve.default.instancePath,(0,M.strConcat)(ve.default.instancePath,r)]}function Jy({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:o}){let n=o?e:(0,M.str)`${e}/${t}`;return r&&(n=(0,M.str)`${n}${(0,Vo.getErrorPath)(r,Vo.Type.Str)}`),[St.schemaPath,n]}function Wy(t,{params:e,message:r},o){let{keyword:n,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;o.push([St.keyword,n],[St.params,typeof e=="function"?e(t):e||(0,M._)`{}`]),c.messages&&o.push([St.message,typeof r=="function"?r(t):r]),c.verbose&&o.push([St.schema,i],[St.parentSchema,(0,M._)`${u}${p}`],[ve.default.data,s]),l&&o.push([St.propertyName,l])}});var Vp=S(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.boolOrEmptySchema=Mt.topBoolOrEmptySchema=void 0;var Yy=Cr(),Xy=O(),Qy=et(),ev={message:"boolean schema is false"};function tv(t){let{gen:e,schema:r,validateName:o}=t;r===!1?Fp(t,!1):typeof r=="object"&&r.$async===!0?e.return(Qy.default.data):(e.assign((0,Xy._)`${o}.errors`,null),e.return(!0))}Mt.topBoolOrEmptySchema=tv;function rv(t,e){let{gen:r,schema:o}=t;o===!1?(r.var(e,!1),Fp(t)):r.var(e,!0)}Mt.boolOrEmptySchema=rv;function Fp(t,e){let{gen:r,data:o}=t,n={gen:r,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Yy.reportError)(n,ev,void 0,e)}});var $i=S(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.getRules=qt.isJSONType=void 0;var ov=["string","number","integer","boolean","null","object","array"],nv=new Set(ov);function sv(t){return typeof t=="string"&&nv.has(t)}qt.isJSONType=sv;function iv(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}qt.getRules=iv});var Si=S(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.shouldUseRule=at.shouldUseGroup=at.schemaHasRulesForType=void 0;function av({schema:t,self:e},r){let o=e.RULES.types[r];return o&&o!==!0&&Hp(t,o)}at.schemaHasRulesForType=av;function Hp(t,e){return e.rules.some(r=>Kp(t,r))}at.shouldUseGroup=Hp;function Kp(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(o=>t[o]!==void 0))}at.shouldUseRule=Kp});var jr=S(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.reportTypeError=_e.checkDataTypes=_e.checkDataType=_e.coerceAndCheckDataType=_e.getJSONTypes=_e.getSchemaTypes=_e.DataType=void 0;var cv=$i(),uv=Si(),lv=Cr(),I=O(),Gp=D(),Lt;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Lt||(_e.DataType=Lt={}));function pv(t){let e=Bp(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}_e.getSchemaTypes=pv;function Bp(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(cv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}_e.getJSONTypes=Bp;function dv(t,e){let{gen:r,data:o,opts:n}=t,s=fv(e,n.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,uv.schemaHasRulesForType)(t,e[0]));if(i){let a=Ti(e,o,n.strictNumbers,Lt.Wrong);r.if(a,()=>{s.length?mv(t,e,s):wi(t)})}return i}_e.coerceAndCheckDataType=dv;var Jp=new Set(["string","number","integer","boolean","null"]);function fv(t,e){return e?t.filter(r=>Jp.has(r)||e==="array"&&r==="array"):[]}function mv(t,e,r){let{gen:o,data:n,opts:s}=t,i=o.let("dataType",(0,I._)`typeof ${n}`),a=o.let("coerced",(0,I._)`undefined`);s.coerceTypes==="array"&&o.if((0,I._)`${i} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,(0,I._)`${n}[0]`).assign(i,(0,I._)`typeof ${n}`).if(Ti(e,n,s.strictNumbers),()=>o.assign(a,n))),o.if((0,I._)`${a} !== undefined`);for(let l of r)(Jp.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);o.else(),wi(t),o.endIf(),o.if((0,I._)`${a} !== undefined`,()=>{o.assign(n,a),hv(t,a)});function c(l){switch(l){case"string":o.elseIf((0,I._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,I._)`"" + ${n}`).elseIf((0,I._)`${n} === null`).assign(a,(0,I._)`""`);return;case"number":o.elseIf((0,I._)`${i} == "boolean" || ${n} === null - || (${i} == "string" && ${n} && ${n} == +${n})`).assign(a,(0,I._)`+${n}`);return;case"integer":o.elseIf((0,I._)`${i} === "boolean" || ${n} === null - || (${i} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(a,(0,I._)`+${n}`);return;case"boolean":o.elseIf((0,I._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(a,!1).elseIf((0,I._)`${n} === "true" || ${n} === 1`).assign(a,!0);return;case"null":o.elseIf((0,I._)`${n} === "" || ${n} === 0 || ${n} === false`),o.assign(a,null);return;case"array":o.elseIf((0,I._)`${i} === "string" || ${i} === "number" - || ${i} === "boolean" || ${n} === null`).assign(a,(0,I._)`[${n}]`)}}}function hv({gen:t,parentData:e,parentDataProperty:r},o){t.if((0,I._)`${e} !== undefined`,()=>t.assign((0,I._)`${e}[${r}]`,o))}function bi(t,e,r,o=Lt.Correct){let n=o===Lt.Correct?I.operators.EQ:I.operators.NEQ,s;switch(t){case"null":return(0,I._)`${e} ${n} null`;case"array":s=(0,I._)`Array.isArray(${e})`;break;case"object":s=(0,I._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,I._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,I._)`typeof ${e} ${n} ${t}`}return o===Lt.Correct?s:(0,I.not)(s);function i(a=I.nil){return(0,I.and)((0,I._)`typeof ${e} == "number"`,a,r?(0,I._)`isFinite(${e})`:I.nil)}}_e.checkDataType=bi;function Ti(t,e,r,o){if(t.length===1)return bi(t[0],e,r,o);let n,s=(0,Gp.toHash)(t);if(s.array&&s.object){let i=(0,I._)`typeof ${e} != "object"`;n=s.null?i:(0,I._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else n=I.nil;s.number&&delete s.integer;for(let i in s)n=(0,I.and)(n,bi(i,e,r,o));return n}_e.checkDataTypes=Ti;var _v={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,I._)`{type: ${t}}`:(0,I._)`{type: ${e}}`};function wi(t){let e=gv(t);(0,lv.reportError)(e,_v)}_e.reportTypeError=wi;function gv(t){let{gen:e,data:r,schema:o}=t,n=(0,Gp.schemaRefOrVal)(t,o,"type");return{gen:e,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:t}}});var Yp=S(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.assignDefaults=void 0;var Ut=O(),yv=D();function vv(t,e){let{properties:r,items:o}=t.schema;if(e==="object"&&r)for(let n in r)Wp(t,n,r[n].default);else e==="array"&&Array.isArray(o)&&o.forEach((n,s)=>Wp(t,s,n.default))}Ho.assignDefaults=vv;function Wp(t,e,r){let{gen:o,compositeRule:n,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Ut._)`${s}${(0,Ut.getProperty)(e)}`;if(n){(0,yv.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ut._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ut._)`${c} || ${a} === null || ${a} === ""`),o.if(c,(0,Ut._)`${a} = ${(0,Ut.stringify)(r)}`)}});var Oe=S(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var W=O(),xi=D(),ct=et(),$v=D();function Sv(t,e){let{gen:r,data:o,it:n}=t;r.if(Ei(r,o,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,W._)`${e}`},!0),t.error()})}F.checkReportMissingProp=Sv;function bv({gen:t,data:e,it:{opts:r}},o,n){return(0,W.or)(...o.map(s=>(0,W.and)(Ei(t,e,s,r.ownProperties),(0,W._)`${n} = ${s}`)))}F.checkMissingProp=bv;function Tv(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Tv;function Xp(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,W._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=Xp;function zi(t,e,r){return(0,W._)`${Xp(t)}.call(${e}, ${r})`}F.isOwnProperty=zi;function wv(t,e,r,o){let n=(0,W._)`${e}${(0,W.getProperty)(r)} !== undefined`;return o?(0,W._)`${n} && ${zi(t,e,r)}`:n}F.propertyInData=wv;function Ei(t,e,r,o){let n=(0,W._)`${e}${(0,W.getProperty)(r)} === undefined`;return o?(0,W.or)(n,(0,W.not)(zi(t,e,r))):n}F.noPropertyInData=Ei;function Qp(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=Qp;function xv(t,e){return Qp(e).filter(r=>!(0,xi.alwaysValidSchema)(t,e[r]))}F.schemaProperties=xv;function zv({schemaCode:t,data:e,it:{gen:r,topSchemaRef:o,schemaPath:n,errorPath:s},it:i},a,c,l){let u=l?(0,W._)`${t}, ${e}, ${o}${n}`:e,p=[[ct.default.instancePath,(0,W.strConcat)(ct.default.instancePath,s)],[ct.default.parentData,i.parentData],[ct.default.parentDataProperty,i.parentDataProperty],[ct.default.rootData,ct.default.rootData]];i.opts.dynamicRef&&p.push([ct.default.dynamicAnchors,ct.default.dynamicAnchors]);let d=(0,W._)`${u}, ${r.object(...p)}`;return c!==W.nil?(0,W._)`${a}.call(${c}, ${d})`:(0,W._)`${a}(${d})`}F.callValidateCode=zv;var Ev=(0,W._)`new RegExp`;function kv({gen:t,it:{opts:e}},r){let o=e.unicodeRegExp?"u":"",{regExp:n}=e.code,s=n(r,o);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,W._)`${n.code==="new RegExp"?Ev:(0,$v.useFunc)(t,n)}(${r}, ${o})`})}F.usePattern=kv;function Pv(t){let{gen:e,data:r,keyword:o,it:n}=t,s=e.name("valid");if(n.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,W._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:xi.Type.Num},s),e.if((0,W.not)(s),a)})}}F.validateArray=Pv;function Rv(t){let{gen:e,schema:r,keyword:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,xi.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:o,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,W._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,W.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}F.validateUnion=Rv});var rd=S(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.validateKeywordUsage=Ve.validSchemaType=Ve.funcKeywordCode=Ve.macroKeywordCode=void 0;var $e=O(),bt=et(),Iv=Oe(),Ov=Cr();function Nv(t,e){let{gen:r,keyword:o,schema:n,parentSchema:s,it:i}=t,a=e.macro.call(i.self,n,s,i),c=td(r,o,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:$e.nil,errSchemaPath:`${i.errSchemaPath}/${o}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Ve.macroKeywordCode=Nv;function Av(t,e){var r;let{gen:o,keyword:n,schema:s,parentSchema:i,$data:a,it:c}=t;jv(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=td(o,n,l),p=o.let("valid");t.block$data(p,d),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function d(){if(e.errors===!1)g(),e.modifying&&ed(t),y(()=>t.error());else{let v=e.async?m():_();e.modifying&&ed(t),y(()=>Cv(t,v))}}function m(){let v=o.let("ruleErrs",null);return o.try(()=>g((0,$e._)`await `),b=>o.assign(p,!1).if((0,$e._)`${b} instanceof ${c.ValidationError}`,()=>o.assign(v,(0,$e._)`${b}.errors`),()=>o.throw(b))),v}function _(){let v=(0,$e._)`${u}.errors`;return o.assign(v,null),g($e.nil),v}function g(v=e.async?(0,$e._)`await `:$e.nil){let b=c.opts.passContext?bt.default.this:bt.default.self,$=!("compile"in e&&!a||e.schema===!1);o.assign(p,(0,$e._)`${v}${(0,Iv.callValidateCode)(t,u,b,$)}`,e.modifying)}function y(v){var b;o.if((0,$e.not)((b=e.valid)!==null&&b!==void 0?b:p),v)}}Ve.funcKeywordCode=Av;function ed(t){let{gen:e,data:r,it:o}=t;e.if(o.parentData,()=>e.assign(r,(0,$e._)`${o.parentData}[${o.parentDataProperty}]`))}function Cv(t,e){let{gen:r}=t;r.if((0,$e._)`Array.isArray(${e})`,()=>{r.assign(bt.default.vErrors,(0,$e._)`${bt.default.vErrors} === null ? ${e} : ${bt.default.vErrors}.concat(${e})`).assign(bt.default.errors,(0,$e._)`${bt.default.vErrors}.length`),(0,Ov.extendErrors)(t)},()=>t.error())}function jv({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function td(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,$e.stringify)(r)})}function Zv(t,e,r=!1){return!e.length||e.some(o=>o==="array"?Array.isArray(t):o==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==o||r&&typeof t>"u")}Ve.validSchemaType=Zv;function Dv({schema:t,opts:e,self:r,errSchemaPath:o},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");let i=n.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ve.validateKeywordUsage=Dv});var nd=S(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.extendSubschemaMode=ut.extendSubschemaData=ut.getSubschema=void 0;var He=O(),od=D();function Mv(t,{keyword:e,schemaProp:r,schema:o,schemaPath:n,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,He._)`${t.schemaPath}${(0,He.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,He._)`${t.schemaPath}${(0,He.getProperty)(e)}${(0,He.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,od.escapeFragment)(r)}`}}if(o!==void 0){if(n===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:n,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}ut.getSubschema=Mv;function qv(t,e,{dataProp:r,dataPropType:o,data:n,dataTypes:s,propertyName:i}){if(n!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:p}=e,d=a.let("data",(0,He._)`${e.data}${(0,He.getProperty)(r)}`,!0);c(d),t.errorPath=(0,He.str)`${l}${(0,od.getErrorPath)(r,o,p.jsPropertySyntax)}`,t.parentDataProperty=(0,He._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(n!==void 0){let l=n instanceof He.Name?n:a.let("data",n,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}ut.extendSubschemaData=qv;function Lv(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:s}){o!==void 0&&(t.compositeRule=o),n!==void 0&&(t.createErrors=n),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}ut.extendSubschemaMode=Lv});var ki=S((jP,sd)=>{"use strict";sd.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),o=s.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;n--!==0;){var i=s[n];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var ad=S((ZP,id)=>{"use strict";var lt=id.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var o=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};Ko(e,o,n,t,"",t)};lt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};lt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};lt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};lt.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};function Ko(t,e,r,o,n,s,i,a,c,l){if(o&&typeof o=="object"&&!Array.isArray(o)){e(o,n,s,i,a,c,l);for(var u in o){var p=o[u];if(Array.isArray(p)){if(u in lt.arrayKeywords)for(var d=0;d{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.getSchemaRefs=we.resolveUrl=we.normalizeId=we._getFullPath=we.getFullPath=we.inlineRef=void 0;var Fv=D(),Vv=ki(),Hv=ad(),Kv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Gv(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Pi(t):e?cd(t)<=e:!1}we.inlineRef=Gv;var Bv=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Pi(t){for(let e in t){if(Bv.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Pi)||typeof r=="object"&&Pi(r))return!0}return!1}function cd(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Kv.has(r)&&(typeof t[r]=="object"&&(0,Fv.eachItem)(t[r],o=>e+=cd(o)),e===1/0))return 1/0}return e}function ud(t,e="",r){r!==!1&&(e=Ft(e));let o=t.parse(e);return ld(t,o)}we.getFullPath=ud;function ld(t,e){return t.serialize(e).split("#")[0]+"#"}we._getFullPath=ld;var Jv=/#\/?$/;function Ft(t){return t?t.replace(Jv,""):""}we.normalizeId=Ft;function Wv(t,e,r){return r=Ft(r),t.resolve(e,r)}we.resolveUrl=Wv;var Yv=/^[a-z_][-a-z0-9._]*$/i;function Xv(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:o}=this.opts,n=Ft(t[r]||e),s={"":n},i=ud(o,n,!1),a={},c=new Set;return Hv(t,{allKeys:!0},(p,d,m,_)=>{if(_===void 0)return;let g=i+d,y=s[_];typeof p[r]=="string"&&(y=v.call(this,p[r])),b.call(this,p.$anchor),b.call(this,p.$dynamicAnchor),s[d]=y;function v($){let z=this.opts.uriResolver.resolve;if($=Ft(y?z(y,$):$),c.has($))throw u($);c.add($);let k=this.refs[$];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?l(p,k.schema,$):$!==Ft(g)&&($[0]==="#"?(l(p,a[$],$),a[$]=p):this.refs[$]=g),$}function b($){if(typeof $=="string"){if(!Yv.test($))throw new Error(`invalid anchor "${$}"`);v.call(this,`#${$}`)}}}),a;function l(p,d,m){if(d!==void 0&&!Vv(p,d))throw u(m)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}we.getSchemaRefs=Xv});var qr=S(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.getData=pt.KeywordCxt=pt.validateFunctionCode=void 0;var hd=Vp(),pd=jr(),Ii=Si(),Go=jr(),Qv=Yp(),Mr=rd(),Ri=nd(),x=O(),P=et(),e$=Zr(),tt=D(),Dr=Cr();function t$(t){if(yd(t)&&(vd(t),gd(t))){n$(t);return}_d(t,()=>(0,hd.topBoolOrEmptySchema)(t))}pt.validateFunctionCode=t$;function _d({gen:t,validateName:e,schema:r,schemaEnv:o,opts:n},s){n.code.es5?t.func(e,(0,x._)`${P.default.data}, ${P.default.valCxt}`,o.$async,()=>{t.code((0,x._)`"use strict"; ${dd(r,n)}`),o$(t,n),t.code(s)}):t.func(e,(0,x._)`${P.default.data}, ${r$(n)}`,o.$async,()=>t.code(dd(r,n)).code(s))}function r$(t){return(0,x._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,x._)`, ${P.default.dynamicAnchors}={}`:x.nil}}={}`}function o$(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,x._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,x._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,x._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,x._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,x._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,x._)`""`),t.var(P.default.parentData,(0,x._)`undefined`),t.var(P.default.parentDataProperty,(0,x._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,x._)`{}`)})}function n$(t){let{schema:e,opts:r,gen:o}=t;_d(t,()=>{r.$comment&&e.$comment&&Sd(t),u$(t),o.let(P.default.vErrors,null),o.let(P.default.errors,0),r.unevaluated&&s$(t),$d(t),d$(t)})}function s$(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,x._)`${r}.evaluated`),e.if((0,x._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,x._)`${t.evaluated}.props`,(0,x._)`undefined`)),e.if((0,x._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,x._)`${t.evaluated}.items`,(0,x._)`undefined`))}function dd(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,x._)`/*# sourceURL=${r} */`:x.nil}function i$(t,e){if(yd(t)&&(vd(t),gd(t))){a$(t,e);return}(0,hd.boolOrEmptySchema)(t,e)}function gd({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function yd(t){return typeof t.schema!="boolean"}function a$(t,e){let{schema:r,gen:o,opts:n}=t;n.$comment&&r.$comment&&Sd(t),l$(t),p$(t);let s=o.const("_errs",P.default.errors);$d(t,s),o.var(e,(0,x._)`${s} === ${P.default.errors}`)}function vd(t){(0,tt.checkUnknownRules)(t),c$(t)}function $d(t,e){if(t.opts.jtd)return fd(t,[],!1,e);let r=(0,pd.getSchemaTypes)(t.schema),o=(0,pd.coerceAndCheckDataType)(t,r);fd(t,r,!o,e)}function c$(t){let{schema:e,errSchemaPath:r,opts:o,self:n}=t;e.$ref&&o.ignoreKeywordsWithRef&&(0,tt.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function u$(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,tt.checkStrictMode)(t,"default is ignored in the schema root")}function l$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,e$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function p$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Sd({gen:t,schemaEnv:e,schema:r,errSchemaPath:o,opts:n}){let s=r.$comment;if(n.$comment===!0)t.code((0,x._)`${P.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let i=(0,x.str)`${o}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,x._)`${P.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function d$(t){let{gen:e,schemaEnv:r,validateName:o,ValidationError:n,opts:s}=t;r.$async?e.if((0,x._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,x._)`new ${n}(${P.default.vErrors})`)):(e.assign((0,x._)`${o}.errors`,P.default.vErrors),s.unevaluated&&f$(t),e.return((0,x._)`${P.default.errors} === 0`))}function f$({gen:t,evaluated:e,props:r,items:o}){r instanceof x.Name&&t.assign((0,x._)`${e}.props`,r),o instanceof x.Name&&t.assign((0,x._)`${e}.items`,o)}function fd(t,e,r,o){let{gen:n,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,tt.schemaHasRulesButRef)(s,u))){n.block(()=>Td(t,"$ref",u.all.$ref.definition));return}c.jtd||m$(t,e),n.block(()=>{for(let d of u.rules)p(d);p(u.post)});function p(d){(0,Ii.shouldUseGroup)(s,d)&&(d.type?(n.if((0,Go.checkDataType)(d.type,i,c.strictNumbers)),md(t,d),e.length===1&&e[0]===d.type&&r&&(n.else(),(0,Go.reportTypeError)(t)),n.endIf()):md(t,d),a||n.if((0,x._)`${P.default.errors} === ${o||0}`))}}function md(t,e){let{gen:r,schema:o,opts:{useDefaults:n}}=t;n&&(0,Qv.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ii.shouldUseRule)(o,s)&&Td(t,s.keyword,s.definition,e.type)})}function m$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(h$(t,e),t.opts.allowUnionTypes||_$(t,e),g$(t,t.dataTypes))}function h$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{bd(t.dataTypes,r)||Oi(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),v$(t,e)}}function _$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Oi(t,"use allowUnionTypes to allow union type keyword")}function g$(t,e){let r=t.self.RULES.all;for(let o in r){let n=r[o];if(typeof n=="object"&&(0,Ii.shouldUseRule)(t.schema,n)){let{type:s}=n.definition;s.length&&!s.some(i=>y$(e,i))&&Oi(t,`missing type "${s.join(",")}" for keyword "${o}"`)}}}function y$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function bd(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function v$(t,e){let r=[];for(let o of t.dataTypes)bd(e,o)?r.push(o):e.includes("integer")&&o==="number"&&r.push("integer");t.dataTypes=r}function Oi(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,tt.checkStrictMode)(t,e,t.opts.strictTypes)}var Bo=class{constructor(e,r,o){if((0,Mr.validateKeywordUsage)(e,r,o),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=o,this.data=e.data,this.schema=e.schema[o],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,tt.schemaRefOrVal)(e,this.schema,o,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",wd(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Mr.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,r,o){this.failResult((0,x.not)(e),r,o)}failResult(e,r,o){this.gen.if(e),o?o():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,x.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,x._)`${r} !== undefined && (${(0,x.or)(this.invalid$data(),e)})`)}error(e,r,o){if(r){this.setParams(r),this._error(e,o),this.setParams({});return}this._error(e,o)}_error(e,r){(e?Dr.reportExtraError:Dr.reportError)(this,this.def.error,r)}$dataError(){(0,Dr.reportError)(this,this.def.$dataError||Dr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Dr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,o=x.nil){this.gen.block(()=>{this.check$data(e,o),r()})}check$data(e=x.nil,r=x.nil){if(!this.$data)return;let{gen:o,schemaCode:n,schemaType:s,def:i}=this;o.if((0,x.or)((0,x._)`${n} === undefined`,r)),e!==x.nil&&o.assign(e,!0),(s.length||i.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),e!==x.nil&&o.assign(e,!1)),o.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:o,def:n,it:s}=this;return(0,x.or)(i(),a());function i(){if(o.length){if(!(r instanceof x.Name))throw new Error("ajv implementation error");let c=Array.isArray(o)?o:[o];return(0,x._)`${(0,Go.checkDataTypes)(c,r,s.opts.strictNumbers,Go.DataType.Wrong)}`}return x.nil}function a(){if(n.validateSchema){let c=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,x._)`!${c}(${r})`}return x.nil}}subschema(e,r){let o=(0,Ri.getSubschema)(this.it,e);(0,Ri.extendSubschemaData)(o,this.it,e),(0,Ri.extendSubschemaMode)(o,e);let n={...this.it,...o,items:void 0,props:void 0};return i$(n,r),n}mergeEvaluated(e,r){let{it:o,gen:n}=this;o.opts.unevaluated&&(o.props!==!0&&e.props!==void 0&&(o.props=tt.mergeEvaluated.props(n,e.props,o.props,r)),o.items!==!0&&e.items!==void 0&&(o.items=tt.mergeEvaluated.items(n,e.items,o.items,r)))}mergeValidEvaluated(e,r){let{it:o,gen:n}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return n.if(r,()=>this.mergeEvaluated(e,x.Name)),!0}};pt.KeywordCxt=Bo;function Td(t,e,r,o){let n=new Bo(t,r,e);"code"in r?r.code(n,o):n.$data&&r.validate?(0,Mr.funcKeywordCode)(n,r):"macro"in r?(0,Mr.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,Mr.funcKeywordCode)(n,r)}var $$=/^\/(?:[^~]|~0|~1)*$/,S$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function wd(t,{dataLevel:e,dataNames:r,dataPathArr:o}){let n,s;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!$$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);n=t,s=P.default.rootData}else{let l=S$.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(n=l[2],n==="#"){if(u>=e)throw new Error(c("property/index",u));return o[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!n)return s}let i=s,a=n.split("/");for(let l of a)l&&(s=(0,x._)`${s}${(0,x.getProperty)((0,tt.unescapeJsonPointer)(l))}`,i=(0,x._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}pt.getData=wd});var Jo=S(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});var Ni=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ai.default=Ni});var Lr=S(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var Ci=Zr(),ji=class extends Error{constructor(e,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,Ci.resolveUrl)(e,r,o),this.missingSchema=(0,Ci.normalizeId)((0,Ci.getFullPath)(e,this.missingRef))}};Zi.default=ji});var Yo=S(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.resolveSchema=Ne.getCompilingSchema=Ne.resolveRef=Ne.compileSchema=Ne.SchemaEnv=void 0;var Ze=O(),b$=Jo(),Tt=et(),De=Zr(),xd=D(),T$=qr(),Vt=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let o;typeof e.schema=="object"&&(o=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,De.normalizeId)(o?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=o?.$async,this.refs={}}};Ne.SchemaEnv=Vt;function Mi(t){let e=zd.call(this,t);if(e)return e;let r=(0,De.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,i=new Ze.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:b$.default,code:(0,Ze._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Tt.default.data,parentData:Tt.default.parentData,parentDataProperty:Tt.default.parentDataProperty,dataNames:[Tt.default.data],dataPathArr:[Ze.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ze.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ze.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ze._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,T$.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Tt.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Tt.default.self}`,`${Tt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:_,items:g}=l;m.evaluated={props:_ instanceof Ze.Name?void 0:_,items:g instanceof Ze.Name?void 0:g,dynamicProps:_ instanceof Ze.Name,dynamicItems:g instanceof Ze.Name},m.source&&(m.source.evaluated=(0,Ze.stringify)(m.evaluated))}return t.validate=m,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Ne.compileSchema=Mi;function w$(t,e,r){var o;r=(0,De.resolveUrl)(this.opts.uriResolver,e,r);let n=t.refs[r];if(n)return n;let s=E$.call(this,t,r);if(s===void 0){let i=(o=t.localRefs)===null||o===void 0?void 0:o[r],{schemaId:a}=this.opts;i&&(s=new Vt({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=x$.call(this,s)}Ne.resolveRef=w$;function x$(t){return(0,De.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Mi.call(this,t)}function zd(t){for(let e of this._compilations)if(z$(e,t))return e}Ne.getCompilingSchema=zd;function z$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function E$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Wo.call(this,t,e)}function Wo(t,e){let r=this.opts.uriResolver.parse(e),o=(0,De._getFullPath)(this.opts.uriResolver,r),n=(0,De.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&o===n)return Di.call(this,r,t);let s=(0,De.normalizeId)(o),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Wo.call(this,t,i);return typeof a?.schema!="object"?void 0:Di.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Mi.call(this,i),s===(0,De.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(n=(0,De.resolveUrl)(this.opts.uriResolver,n,l)),new Vt({schema:a,schemaId:c,root:t,baseId:n})}return Di.call(this,r,i)}}Ne.resolveSchema=Wo;var k$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Di(t,{baseId:e,schema:r,root:o}){var n;if(((n=t.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,xd.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!k$.has(a)&&l&&(e=(0,De.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,xd.schemaHasRulesButRef)(r,this.RULES)){let a=(0,De.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Wo.call(this,o,a)}let{schemaId:i}=this.opts;if(s=s||new Vt({schema:r,schemaId:i,root:o,baseId:e}),s.schema!==s.root.schema)return s}});var Ed=S((FP,P$)=>{P$.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ui=S((VP,Nd)=>{"use strict";var R$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Pd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),qi=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Rd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),I$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Li(t){let e="",r=0,o=0;for(o=0;o=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o];break}for(o+=1;o=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o]}return e}var O$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function kd(t){return t.length=0,!0}function N$(t,e,r){if(t.length){let o=Li(t);if(o!=="")e.push(o);else return r.error=!0,!1;t.length=0}return!0}function A$(t){let e=0,r={error:!1,address:"",zone:""},o=[],n=[],s=!1,i=!1,a=N$;for(let c=0;c7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),o.push(":");continue}else if(l==="%"){if(!a(n,o,r))break;a=kd}else{n.push(l);continue}}return n.length&&(a===kd?r.zone=n.join(""):i?o.push(n.join("")):o.push(Li(n))),r.address=o.join(""),r}function Id(t){if(C$(t,":")<2)return{host:t,isIPV6:!1};let e=A$(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,o=e.address;return e.zone&&(r+="%"+e.zone,o+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:o}}}function C$(t,e){let r=0;for(let o=0;oZ$[o])}function q$(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let o=0;o{"use strict";var{isUUID:V$}=Ui(),H$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,K$=["http","https","ws","wss","urn","urn:uuid"];function G$(t){return K$.indexOf(t)!==-1}function Fi(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Ad(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Cd(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function B$(t){return t.secure=Fi(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function J$(t){if((t.port===(Fi(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function W$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(H$);if(r){let o=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let n=`${o}:${e.nid||t.nid}`,s=Vi(n);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Y$(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",o=t.nid.toLowerCase(),n=`${r}:${e.nid||o}`,s=Vi(n);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${o||e.nid}:${a}`,e.skipEscape=!0,i}function X$(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!V$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Q$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var jd={scheme:"http",domainHost:!0,parse:Ad,serialize:Cd},e0={scheme:"https",domainHost:jd.domainHost,parse:Ad,serialize:Cd},Xo={scheme:"ws",domainHost:!0,parse:B$,serialize:J$},t0={scheme:"wss",domainHost:Xo.domainHost,parse:Xo.parse,serialize:Xo.serialize},r0={scheme:"urn",parse:W$,serialize:Y$,skipNormalize:!0},o0={scheme:"urn:uuid",parse:X$,serialize:Q$,skipNormalize:!0},Qo={http:jd,https:e0,ws:Xo,wss:t0,urn:r0,"urn:uuid":o0};Object.setPrototypeOf(Qo,null);function Vi(t){return t&&(Qo[t]||Qo[t.toLowerCase()])||void 0}Zd.exports={wsIsSecure:Fi,SCHEMES:Qo,isValidSchemeName:G$,getSchemeHandler:Vi}});var Fd=S((KP,rn)=>{"use strict";var{normalizeIPv6:n0,removeDotSegments:Ur,recomposeAuthority:s0,normalizePercentEncoding:i0,normalizePathEncoding:a0,escapePreservingEscapes:c0,reescapeHostDelimiters:u0,isIPv4:l0,nonSimpleDomain:p0}=Ui(),{SCHEMES:d0,getSchemeHandler:qd}=Dd();function f0(t,e){return typeof t=="string"?t=$0(t,e):typeof t=="object"&&(t=tn(wt(t,e),e)),t}function m0(t,e,r){let o=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:n,malformedAuthorityOrPort:s}=en(t,o),{parsed:i,malformedAuthorityOrPort:a}=en(e,o);if(s||a)throw new Error(n.error||i.error||"URI is malformed.");let c=Ld(n,i,o,!0);return o.skipEscape=!0,wt(c,o)}function Ld(t,e,r,o){let n={};return o||(t=tn(wt(t,r),r),e=tn(wt(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Ur(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Ur(e.path||""),n.query=e.query):(e.path?(e.path[0]==="/"?n.path=Ur(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?n.path="/"+e.path:t.path?n.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=Ur(n.path)),n.query=e.query):(n.path=t.path,e.query!==void 0?n.query=e.query:n.query=t.query),n.userinfo=t.userinfo,n.host=t.host,n.port=t.port),n.scheme=t.scheme),n.fragment=e.fragment,n}function h0(t,e,r){let o=Md(t,r),n=Md(e,r);return o!==void 0&&n!==void 0&&o.toLowerCase()===n.toLowerCase()}function wt(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},o=Object.assign({},e),n=[],s=qd(o.scheme||r.scheme);s&&s.serialize&&s.serialize(r,o),r.path!==void 0&&(o.skipEscape?r.path=i0(r.path):(r.path=c0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),o.reference!=="suffix"&&r.scheme&&n.push(r.scheme,":");let i=s0(r);if(i!==void 0&&(o.reference!=="suffix"&&n.push("//"),n.push(i),r.path&&r.path[0]!=="/"&&n.push("/")),r.path!==void 0){let a=r.path;!o.absolutePath&&(!s||!s.absolutePath)&&(a=Ur(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),n.push(a)}return r.query!==void 0&&n.push("?",r.query),r.fragment!==void 0&&n.push("#",r.fragment),n.join("")}var _0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,g0=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,y0=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function v0(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function en(t,e){let r=Object.assign({},e),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(g0);i!==null&&i[1].indexOf("\\")!==-1&&(o.error="URI authority must not contain a literal backslash.",n=!0);let a=t.match(y0);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(o.error=o.error||"URI authority must not contain a literal backslash.",n=!0):l.length!==u.length&&(o.error=o.error||"URI authority introducer must not contain whitespace.",n=!0))}let c=t.match(_0);if(c){o.scheme=c[1],o.userinfo=c[3],o.host=c[4],o.port=parseInt(c[5],10),o.path=c[6]||"",o.query=c[7],o.fragment=c[8],isNaN(o.port)&&(o.port=c[5]);let l=v0(o,c);if(l!==void 0&&(o.error=o.error||l,n=!0),o.host)if(l0(o.host)===!1){let d=n0(o.host);o.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==o.reference&&(o.error=o.error||"URI is not a "+r.reference+" reference.");let u=qd(r.scheme||o.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&o.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&p0(o.host))try{o.host=new URL("http://"+o.host).hostname}catch(p){o.error=o.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(o.scheme!==void 0&&(o.scheme=unescape(o.scheme)),o.host!==void 0&&(o.host=u0(unescape(o.host),s))),o.path&&(o.path=a0(o.path)),o.fragment))try{o.fragment=encodeURI(decodeURIComponent(o.fragment))}catch{o.error=o.error||"URI malformed"}u&&u.parse&&u.parse(o,r)}else o.error=o.error||"URI can not be parsed.";return{parsed:o,malformedAuthorityOrPort:n}}function tn(t,e){return en(t,e).parsed}function $0(t,e){return Ud(t,e).normalized}function Ud(t,e){let{parsed:r,malformedAuthorityOrPort:o}=en(t,e);return{normalized:o?t:wt(r,e),malformedAuthorityOrPort:o}}function Md(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:o}=Ud(t,e);return o?void 0:r}if(typeof t=="object")return wt(t,e)}var Hi={SCHEMES:d0,normalize:f0,resolve:m0,resolveComponent:Ld,equal:h0,serialize:wt,parse:tn};rn.exports=Hi;rn.exports.default=Hi;rn.exports.fastUri=Hi});var Hd=S(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});var Vd=Fd();Vd.code='require("ajv/dist/runtime/uri").default';Ki.default=Vd});var Qd=S(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=void 0;var S0=qr();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return S0.KeywordCxt}});var Ht=O();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Ht._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Ht.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Ht.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Ht.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Ht.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Ht.CodeGen}});var b0=Jo(),Wd=Lr(),T0=$i(),Fr=Yo(),w0=O(),Vr=Zr(),on=jr(),Bi=D(),Kd=Ed(),x0=Hd(),Yd=(t,e)=>new RegExp(t,e);Yd.code="new RegExp";var z0=["removeAdditional","useDefaults","coerceTypes"],E0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),k0={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},P0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Gd=200;function R0(t){var e,r,o,n,s,i,a,c,l,u,p,d,m,_,g,y,v,b,$,z,k,ge,Ee,kt,jn;let er=t.strict,Zn=(e=t.code)===null||e===void 0?void 0:e.optimize,nc=Zn===!0||Zn===void 0?1:Zn||0,sc=(o=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&o!==void 0?o:Yd,ph=(n=t.uriResolver)!==null&&n!==void 0?n:x0.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:er)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:er)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:er)!==null&&u!==void 0?u:"log",strictTuples:(d=(p=t.strictTuples)!==null&&p!==void 0?p:er)!==null&&d!==void 0?d:"log",strictRequired:(_=(m=t.strictRequired)!==null&&m!==void 0?m:er)!==null&&_!==void 0?_:!1,code:t.code?{...t.code,optimize:nc,regExp:sc}:{optimize:nc,regExp:sc},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Gd,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Gd,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:($=t.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(z=t.schemaId)!==null&&z!==void 0?z:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(ge=t.validateSchema)!==null&&ge!==void 0?ge:!0,validateFormats:(Ee=t.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:(kt=t.unicodeRegExp)!==null&&kt!==void 0?kt:!0,int32range:(jn=t.int32range)!==null&&jn!==void 0?jn:!0,uriResolver:ph}}var Hr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...R0(e)};let{es5:r,lines:o}=this.opts.code;this.scope=new w0.ValueScope({scope:{},prefixes:E0,es5:r,lines:o}),this.logger=j0(e.logger);let n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,T0.getRules)(),Bd.call(this,k0,e,"NOT SUPPORTED"),Bd.call(this,P0,e,"DEPRECATED","warn"),this._metaOpts=A0.call(this),e.formats&&O0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&N0.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),I0.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:o}=this.opts,n=Kd;o==="id"&&(n={...Kd},n.id=n.$id,delete n.$id),r&&e&&this.addMetaSchema(n,n[o],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let o;if(typeof e=="string"){if(o=this.getSchema(e),!o)throw new Error(`no schema with key or ref "${e}"`)}else o=this.compile(e);let n=o(r);return"$async"in o||(this.errors=o.errors),n}compile(e,r){let o=this._addSchema(e,r);return o.validate||this._compileSchemaEnv(o)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return n.call(this,e,r);async function n(u,p){await s.call(this,u.$schema);let d=this._addSchema(u,p);return d.validate||i.call(this,d)}async function s(u){u&&!this.getSchema(u)&&await n.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof Wd.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;try{return await(this._loading[u]=o(u))}finally{delete this._loading[u]}}}addSchema(e,r,o,n=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,o,n);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Vr.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,o,r,n,!0),this}addMetaSchema(e,r,o=this.opts.validateSchema){return this.addSchema(e,r,!0,o),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let o;if(o=e.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(o,e);if(!n&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return n}getSchema(e){let r;for(;typeof(r=Jd.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:o}=this.opts,n=new Fr.SchemaEnv({schema:{},schemaId:o});if(r=Fr.resolveSchema.call(this,n,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Jd.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let o=e[this.opts.schemaId];return o&&(o=(0,Vr.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let o;if(typeof e=="string")o=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=o);else if(typeof e=="object"&&r===void 0){if(r=e,o=r.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(D0.call(this,o,r),!r)return(0,Bi.eachItem)(o,s=>Gi.call(this,s)),this;q0.call(this,r);let n={...r,type:(0,on.getJSONTypes)(r.type),schemaType:(0,on.getJSONTypes)(r.schemaType)};return(0,Bi.eachItem)(o,n.type.length===0?s=>Gi.call(this,s,n):s=>n.type.forEach(i=>Gi.call(this,s,n,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let o of r.rules){let n=o.rules.findIndex(s=>s.keyword===e);n>=0&&o.rules.splice(n,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:o="data"}={}){return!e||e.length===0?"No errors":e.map(n=>`${o}${n.instancePath} ${n.message}`).reduce((n,s)=>n+r+s)}$dataMetaSchema(e,r){let o=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of r){let s=n.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in o){let c=o[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=Xd(u))}}return e}_removeAllSchemas(e,r){for(let o in e){let n=e[o];(!r||r.test(o))&&(typeof n=="string"?delete e[o]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[o]))}}_addSchema(e,r,o,n=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;o=(0,Vr.normalizeId)(i||o);let l=Vr.getSchemaRefs.call(this,e,o);return c=new Fr.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:o,localRefs:l}),this._cache.set(c.schema,c),s&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=c),n&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Fr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Fr.compileSchema.call(this,e)}finally{this.opts=r}}};Hr.ValidationError=b0.default;Hr.MissingRefError=Wd.default;le.default=Hr;function Bd(t,e,r,o="error"){for(let n in t){let s=n;s in e&&this.logger[o](`${r}: option ${n}. ${t[s]}`)}}function Jd(t){return t=(0,Vr.normalizeId)(t),this.schemas[t]||this.refs[t]}function I0(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function O0(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function N0(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function A0(){let t={...this.opts};for(let e of z0)delete t[e];return t}var C0={log(){},warn(){},error(){}};function j0(t){if(t===!1)return C0;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Z0=/^[a-z_$][a-z0-9_$:-]*$/i;function D0(t,e){let{RULES:r}=this;if((0,Bi.eachItem)(t,o=>{if(r.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!Z0.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Gi(t,e,r){var o;let n=e?.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=n?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,on.getJSONTypes)(e.type),schemaType:(0,on.getJSONTypes)(e.schemaType)}};e.before?M0.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(o=e.implements)===null||o===void 0||o.forEach(c=>this.addKeyword(c))}function M0(t,e,r){let o=t.rules.findIndex(n=>n.keyword===r);o>=0?t.rules.splice(o,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function q0(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Xd(e)),t.validateSchema=this.compile(e,!0))}var L0={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xd(t){return{anyOf:[t,L0]}}});var ef=S(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});var U0={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ji.default=U0});var nf=S(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.callRef=xt.getValidate=void 0;var F0=Lr(),tf=Oe(),xe=O(),Kt=et(),rf=Yo(),nn=D(),V0={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:o}=t,{baseId:n,schemaEnv:s,validateName:i,opts:a,self:c}=o,{root:l}=s;if((r==="#"||r==="#/")&&n===l.baseId)return p();let u=rf.resolveRef.call(c,l,n,r);if(u===void 0)throw new F0.default(o.opts.uriResolver,n,r);if(u instanceof rf.SchemaEnv)return d(u);return m(u);function p(){if(s===l)return sn(t,i,s,s.$async);let _=e.scopeValue("root",{ref:l});return sn(t,(0,xe._)`${_}.validate`,l,l.$async)}function d(_){let g=of(t,_);sn(t,g,_,_.$async)}function m(_){let g=e.scopeValue("schema",a.code.source===!0?{ref:_,code:(0,xe.stringify)(_)}:{ref:_}),y=e.name("valid"),v=t.subschema({schema:_,dataTypes:[],schemaPath:xe.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function of(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,xe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}xt.getValidate=of;function sn(t,e,r,o){let{gen:n,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Kt.default.this:xe.nil;o?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let _=n.let("valid");n.try(()=>{n.code((0,xe._)`await ${(0,tf.callValidateCode)(t,e,l)}`),m(e),i||n.assign(_,!0)},g=>{n.if((0,xe._)`!(${g} instanceof ${s.ValidationError})`,()=>n.throw(g)),d(g),i||n.assign(_,!1)}),t.ok(_)}function p(){t.result((0,tf.callValidateCode)(t,e,l),()=>m(e),()=>d(e))}function d(_){let g=(0,xe._)`${_}.errors`;n.assign(Kt.default.vErrors,(0,xe._)`${Kt.default.vErrors} === null ? ${g} : ${Kt.default.vErrors}.concat(${g})`),n.assign(Kt.default.errors,(0,xe._)`${Kt.default.vErrors}.length`)}function m(_){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=nn.mergeEvaluated.props(n,y.props,s.props));else{let v=n.var("props",(0,xe._)`${_}.evaluated.props`);s.props=nn.mergeEvaluated.props(n,v,s.props,xe.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=nn.mergeEvaluated.items(n,y.items,s.items));else{let v=n.var("items",(0,xe._)`${_}.evaluated.items`);s.items=nn.mergeEvaluated.items(n,v,s.items,xe.Name)}}}xt.callRef=sn;xt.default=V0});var sf=S(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});var H0=ef(),K0=nf(),G0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",H0.default,K0.default];Wi.default=G0});var af=S(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});var an=O(),dt=an.operators,cn={maximum:{okStr:"<=",ok:dt.LTE,fail:dt.GT},minimum:{okStr:">=",ok:dt.GTE,fail:dt.LT},exclusiveMaximum:{okStr:"<",ok:dt.LT,fail:dt.GTE},exclusiveMinimum:{okStr:">",ok:dt.GT,fail:dt.LTE}},B0={message:({keyword:t,schemaCode:e})=>(0,an.str)`must be ${cn[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,an._)`{comparison: ${cn[t].okStr}, limit: ${e}}`},J0={keyword:Object.keys(cn),type:"number",schemaType:"number",$data:!0,error:B0,code(t){let{keyword:e,data:r,schemaCode:o}=t;t.fail$data((0,an._)`${r} ${cn[e].fail} ${o} || isNaN(${r})`)}};Yi.default=J0});var cf=S(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});var Kr=O(),W0={message:({schemaCode:t})=>(0,Kr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Kr._)`{multipleOf: ${t}}`},Y0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:W0,code(t){let{gen:e,data:r,schemaCode:o,it:n}=t,s=n.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Kr._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Kr._)`${i} !== parseInt(${i})`;t.fail$data((0,Kr._)`(${o} === 0 || (${i} = ${r}/${o}, ${a}))`)}};Xi.default=Y0});var lf=S(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});function uf(t){let e=t.length,r=0,o=0,n;for(;o=55296&&n<=56319&&o{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var zt=O(),X0=D(),Q0=lf(),eS={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,zt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,zt._)`{limit: ${t}}`},tS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eS,code(t){let{keyword:e,data:r,schemaCode:o,it:n}=t,s=e==="maxLength"?zt.operators.GT:zt.operators.LT,i=n.opts.unicode===!1?(0,zt._)`${r}.length`:(0,zt._)`${(0,X0.useFunc)(t.gen,Q0.default)}(${r})`;t.fail$data((0,zt._)`${i} ${s} ${o}`)}};ea.default=tS});var df=S(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var rS=Oe(),oS=D(),Gt=O(),nS={message:({schemaCode:t})=>(0,Gt.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Gt._)`{pattern: ${t}}`},sS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:nS,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(o){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,Gt._)`new RegExp`:(0,oS.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Gt._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Gt._)`!${u}`)}else{let c=(0,rS.usePattern)(t,n);t.fail$data((0,Gt._)`!${c}.test(${r})`)}}};ta.default=sS});var ff=S(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var Gr=O(),iS={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Gr.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Gr._)`{limit: ${t}}`},aS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:iS,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxProperties"?Gr.operators.GT:Gr.operators.LT;t.fail$data((0,Gr._)`Object.keys(${r}).length ${n} ${o}`)}};ra.default=aS});var mf=S(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});var Br=Oe(),Jr=O(),cS=D(),uS={message:({params:{missingProperty:t}})=>(0,Jr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Jr._)`{missingProperty: ${t}}`},lS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:uS,code(t){let{gen:e,schema:r,schemaCode:o,data:n,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:_}=t.it;for(let g of r)if(m?.[g]===void 0&&!_.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,cS.checkStrictMode)(i,v,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Jr.nil,p);else for(let m of r)(0,Br.checkReportMissingProp)(t,m)}function u(){let m=e.let("missing");if(c||s){let _=e.let("valid",!0);t.block$data(_,()=>d(m,_)),t.ok(_)}else e.if((0,Br.checkMissingProp)(t,r,m)),(0,Br.reportMissingProp)(t,m),e.else()}function p(){e.forOf("prop",o,m=>{t.setParams({missingProperty:m}),e.if((0,Br.noPropertyInData)(e,n,m,a.ownProperties),()=>t.error())})}function d(m,_){t.setParams({missingProperty:m}),e.forOf(m,o,()=>{e.assign(_,(0,Br.propertyInData)(e,n,m,a.ownProperties)),e.if((0,Jr.not)(_),()=>{t.error(),e.break()})},Jr.nil)}}};oa.default=lS});var hf=S(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});var Wr=O(),pS={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Wr.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Wr._)`{limit: ${t}}`},dS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:pS,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxItems"?Wr.operators.GT:Wr.operators.LT;t.fail$data((0,Wr._)`${r}.length ${n} ${o}`)}};na.default=dS});var un=S(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});var _f=ki();_f.code='require("ajv/dist/runtime/equal").default';sa.default=_f});var gf=S(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});var ia=jr(),pe=O(),fS=D(),mS=un(),hS={message:({params:{i:t,j:e}})=>(0,pe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pe._)`{i: ${t}, j: ${e}}`},_S={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:hS,code(t){let{gen:e,data:r,$data:o,schema:n,parentSchema:s,schemaCode:i,it:a}=t;if(!o&&!n)return;let c=e.let("valid"),l=s.items?(0,ia.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,pe._)`${i} === false`),t.ok(c);function u(){let _=e.let("i",(0,pe._)`${r}.length`),g=e.let("j");t.setParams({i:_,j:g}),e.assign(c,!0),e.if((0,pe._)`${_} > 1`,()=>(p()?d:m)(_,g))}function p(){return l.length>0&&!l.some(_=>_==="object"||_==="array")}function d(_,g){let y=e.name("item"),v=(0,ia.checkDataTypes)(l,y,a.opts.strictNumbers,ia.DataType.Wrong),b=e.const("indices",(0,pe._)`{}`);e.for((0,pe._)`;${_}--;`,()=>{e.let(y,(0,pe._)`${r}[${_}]`),e.if(v,(0,pe._)`continue`),l.length>1&&e.if((0,pe._)`typeof ${y} == "string"`,(0,pe._)`${y} += "_"`),e.if((0,pe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(g,(0,pe._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,pe._)`${b}[${y}] = ${_}`)})}function m(_,g){let y=(0,fS.useFunc)(e,mS.default),v=e.name("outer");e.label(v).for((0,pe._)`;${_}--;`,()=>e.for((0,pe._)`${g} = ${_}; ${g}--;`,()=>e.if((0,pe._)`${y}(${r}[${_}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};aa.default=_S});var yf=S(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});var ca=O(),gS=D(),yS=un(),vS={message:"must be equal to constant",params:({schemaCode:t})=>(0,ca._)`{allowedValue: ${t}}`},$S={keyword:"const",$data:!0,error:vS,code(t){let{gen:e,data:r,$data:o,schemaCode:n,schema:s}=t;o||s&&typeof s=="object"?t.fail$data((0,ca._)`!${(0,gS.useFunc)(e,yS.default)}(${r}, ${n})`):t.fail((0,ca._)`${s} !== ${r}`)}};ua.default=$S});var vf=S(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});var Yr=O(),SS=D(),bS=un(),TS={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Yr._)`{allowedValues: ${t}}`},wS={keyword:"enum",schemaType:"array",$data:!0,error:TS,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:s,it:i}=t;if(!o&&n.length===0)throw new Error("enum must have non-empty array");let a=n.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,SS.useFunc)(e,bS.default)),u;if(a||o)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(n))throw new Error("ajv implementation error");let m=e.const("vSchema",s);u=(0,Yr.or)(...n.map((_,g)=>d(m,g)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,m=>e.if((0,Yr._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function d(m,_){let g=n[_];return typeof g=="object"&&g!==null?(0,Yr._)`${l()}(${r}, ${m}[${_}])`:(0,Yr._)`${r} === ${g}`}}};la.default=wS});var $f=S(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});var xS=af(),zS=cf(),ES=pf(),kS=df(),PS=ff(),RS=mf(),IS=hf(),OS=gf(),NS=yf(),AS=vf(),CS=[xS.default,zS.default,ES.default,kS.default,PS.default,RS.default,IS.default,OS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},NS.default,AS.default];pa.default=CS});var fa=S(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.validateAdditionalItems=void 0;var Et=O(),da=D(),jS={message:({params:{len:t}})=>(0,Et.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Et._)`{limit: ${t}}`},ZS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:jS,code(t){let{parentSchema:e,it:r}=t,{items:o}=e;if(!Array.isArray(o)){(0,da.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Sf(t,o)}};function Sf(t,e){let{gen:r,schema:o,data:n,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Et._)`${n}.length`);if(o===!1)t.setParams({len:e.length}),t.pass((0,Et._)`${a} <= ${e.length}`);else if(typeof o=="object"&&!(0,da.alwaysValidSchema)(i,o)){let l=r.var("valid",(0,Et._)`${a} <= ${e.length}`);r.if((0,Et.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:da.Type.Num},l),i.allErrors||r.if((0,Et.not)(l),()=>r.break())})}}Xr.validateAdditionalItems=Sf;Xr.default=ZS});var ma=S(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.validateTuple=void 0;var bf=O(),ln=D(),DS=Oe(),MS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Tf(t,"additionalItems",e);r.items=!0,!(0,ln.alwaysValidSchema)(r,e)&&t.ok((0,DS.validateArray)(t))}};function Tf(t,e,r=t.schema){let{gen:o,parentSchema:n,data:s,keyword:i,it:a}=t;u(n),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ln.mergeEvaluated.items(o,r.length,a.items));let c=o.name("valid"),l=o.const("len",(0,bf._)`${s}.length`);r.forEach((p,d)=>{(0,ln.alwaysValidSchema)(a,p)||(o.if((0,bf._)`${l} > ${d}`,()=>t.subschema({keyword:i,schemaProp:d,dataProp:d},c)),t.ok(c))});function u(p){let{opts:d,errSchemaPath:m}=a,_=r.length,g=_===p.minItems&&(_===p.maxItems||p[e]===!1);if(d.strictTuples&&!g){let y=`"${i}" is ${_}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,ln.checkStrictMode)(a,y,d.strictTuples)}}}Qr.validateTuple=Tf;Qr.default=MS});var wf=S(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});var qS=ma(),LS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,qS.validateTuple)(t,"items")};ha.default=LS});var zf=S(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});var xf=O(),US=D(),FS=Oe(),VS=fa(),HS={message:({params:{len:t}})=>(0,xf.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xf._)`{limit: ${t}}`},KS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:HS,code(t){let{schema:e,parentSchema:r,it:o}=t,{prefixItems:n}=r;o.items=!0,!(0,US.alwaysValidSchema)(o,e)&&(n?(0,VS.validateAdditionalItems)(t,n):t.ok((0,FS.validateArray)(t)))}};_a.default=KS});var Ef=S(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});var Ae=O(),pn=D(),GS={message:({params:{min:t,max:e}})=>e===void 0?(0,Ae.str)`must contain at least ${t} valid item(s)`:(0,Ae.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ae._)`{minContains: ${t}}`:(0,Ae._)`{minContains: ${t}, maxContains: ${e}}`},BS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:GS,code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:s}=t,i,a,{minContains:c,maxContains:l}=o;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Ae._)`${n}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,pn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,pn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,pn.alwaysValidSchema)(s,r)){let g=(0,Ae._)`${u} >= ${i}`;a!==void 0&&(g=(0,Ae._)`${g} && ${u} <= ${a}`),t.pass(g);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?m(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Ae._)`${n}.length > 0`,d)):(e.let(p,!1),d()),t.result(p,()=>t.reset());function d(){let g=e.name("_valid"),y=e.let("count",0);m(g,()=>e.if(g,()=>_(y)))}function m(g,y){e.forRange("i",0,u,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:pn.Type.Num,compositeRule:!0},g),y()})}function _(g){e.code((0,Ae._)`${g}++`),a===void 0?e.if((0,Ae._)`${g} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Ae._)`${g} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Ae._)`${g} >= ${i}`,()=>e.assign(p,!0)))}}};ga.default=BS});var Rf=S(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.validateSchemaDeps=Ke.validatePropertyDeps=Ke.error=void 0;var ya=O(),JS=D(),eo=Oe();Ke.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let o=e===1?"property":"properties";return(0,ya.str)`must have ${o} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:o}})=>(0,ya._)`{property: ${t}, - missingProperty: ${o}, - depsCount: ${e}, - deps: ${r}}`};var WS={keyword:"dependencies",type:"object",schemaType:"object",error:Ke.error,code(t){let[e,r]=YS(t);kf(t,e),Pf(t,r)}};function YS({schema:t}){let e={},r={};for(let o in t){if(o==="__proto__")continue;let n=Array.isArray(t[o])?e:r;n[o]=t[o]}return[e,r]}function kf(t,e=t.schema){let{gen:r,data:o,it:n}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,eo.propertyInData)(r,o,i,n.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),n.allErrors?r.if(c,()=>{for(let l of a)(0,eo.checkReportMissingProp)(t,l)}):(r.if((0,ya._)`${c} && (${(0,eo.checkMissingProp)(t,a,s)})`),(0,eo.reportMissingProp)(t,s),r.else())}}Ke.validatePropertyDeps=kf;function Pf(t,e=t.schema){let{gen:r,data:o,keyword:n,it:s}=t,i=r.name("valid");for(let a in e)(0,JS.alwaysValidSchema)(s,e[a])||(r.if((0,eo.propertyInData)(r,o,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:n,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ke.validateSchemaDeps=Pf;Ke.default=WS});var Of=S(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});var If=O(),XS=D(),QS={message:"property name must be valid",params:({params:t})=>(0,If._)`{propertyName: ${t.propertyName}}`},eb={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:QS,code(t){let{gen:e,schema:r,data:o,it:n}=t;if((0,XS.alwaysValidSchema)(n,r))return;let s=e.name("valid");e.forIn("key",o,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,If.not)(s),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(s)}};va.default=eb});var Sa=S($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});var dn=Oe(),Me=O(),tb=et(),fn=D(),rb={message:"must NOT have additional properties",params:({params:t})=>(0,Me._)`{additionalProperty: ${t.additionalProperty}}`},ob={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rb,code(t){let{gen:e,schema:r,parentSchema:o,data:n,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,fn.alwaysValidSchema)(i,r))return;let l=(0,dn.allSchemaProperties)(o.properties),u=(0,dn.allSchemaProperties)(o.patternProperties);p(),t.ok((0,Me._)`${s} === ${tb.default.errors}`);function p(){e.forIn("key",n,y=>{!l.length&&!u.length?_(y):e.if(d(y),()=>_(y))})}function d(y){let v;if(l.length>8){let b=(0,fn.schemaRefOrVal)(i,o.properties,"properties");v=(0,dn.isOwnProperty)(e,b,y)}else l.length?v=(0,Me.or)(...l.map(b=>(0,Me._)`${y} === ${b}`)):v=Me.nil;return u.length&&(v=(0,Me.or)(v,...u.map(b=>(0,Me._)`${(0,dn.usePattern)(t,b)}.test(${y})`))),(0,Me.not)(v)}function m(y){e.code((0,Me._)`delete ${n}[${y}]`)}function _(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,fn.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(g(y,v,!1),e.if((0,Me.not)(v),()=>{t.reset(),m(y)})):(g(y,v),a||e.if((0,Me.not)(v),()=>e.break()))}}function g(y,v,b){let $={keyword:"additionalProperties",dataProp:y,dataPropType:fn.Type.Str};b===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema($,v)}}};$a.default=ob});var Cf=S(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});var nb=qr(),Nf=Oe(),ba=D(),Af=Sa(),sb={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:s}=t;s.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&Af.default.code(new nb.KeywordCxt(s,Af.default,"additionalProperties"));let i=(0,Nf.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=ba.mergeEvaluated.props(e,(0,ba.toHash)(i),s.props));let a=i.filter(p=>!(0,ba.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,Nf.propertyInData)(e,n,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Ta.default=sb});var Mf=S(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});var jf=Oe(),mn=O(),Zf=D(),Df=D(),ib={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:o,parentSchema:n,it:s}=t,{opts:i}=s,a=(0,jf.allSchemaProperties)(r),c=a.filter(g=>(0,Zf.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&n.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof mn.Name)&&(s.props=(0,Df.evaluatedPropsToName)(e,s.props));let{props:p}=s;d();function d(){for(let g of a)l&&m(g),s.allErrors?_(g):(e.var(u,!0),_(g),e.if(u))}function m(g){for(let y in l)new RegExp(g).test(y)&&(0,Zf.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function _(g){e.forIn("key",o,y=>{e.if((0,mn._)`${(0,jf.usePattern)(t,g)}.test(${y})`,()=>{let v=c.includes(g);v||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Df.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,mn._)`${p}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,mn.not)(u),()=>e.break())})})}}};wa.default=ib});var qf=S(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});var ab=D(),cb={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:o}=t;if((0,ab.alwaysValidSchema)(o,r)){t.fail();return}let n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};xa.default=cb});var Lf=S(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var ub=Oe(),lb={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ub.validateUnion,error:{message:"must match a schema in anyOf"}};za.default=lb});var Uf=S(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var hn=O(),pb=D(),db={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,hn._)`{passingSchemas: ${t.passing}}`},fb={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:db,code(t){let{gen:e,schema:r,parentSchema:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,p)=>{let d;(0,pb.alwaysValidSchema)(n,u)?e.var(c,!0):d=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,hn._)`${c} && ${i}`).assign(i,!1).assign(a,(0,hn._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),d&&t.mergeEvaluated(d,hn.Name)})})}}};Ea.default=fb});var Ff=S(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});var mb=D(),hb={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let n=e.name("valid");r.forEach((s,i)=>{if((0,mb.alwaysValidSchema)(o,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},n);t.ok(n),t.mergeEvaluated(a)})}};ka.default=hb});var Kf=S(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});var _n=O(),Hf=D(),_b={message:({params:t})=>(0,_n.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,_n._)`{failingKeyword: ${t.ifClause}}`},gb={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:_b,code(t){let{gen:e,parentSchema:r,it:o}=t;r.then===void 0&&r.else===void 0&&(0,Hf.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let n=Vf(o,"then"),s=Vf(o,"else");if(!n&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),n&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else n?e.if(a,l("then")):e.if((0,_n.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,p){return()=>{let d=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(d,i),p?e.assign(p,(0,_n._)`${u}`):t.setParams({ifClause:u})}}}};function Vf(t,e){let r=t.schema[e];return r!==void 0&&!(0,Hf.alwaysValidSchema)(t,r)}Pa.default=gb});var Gf=S(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});var yb=D(),vb={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,yb.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ra.default=vb});var Bf=S(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});var $b=fa(),Sb=wf(),bb=ma(),Tb=zf(),wb=Ef(),xb=Rf(),zb=Of(),Eb=Sa(),kb=Cf(),Pb=Mf(),Rb=qf(),Ib=Lf(),Ob=Uf(),Nb=Ff(),Ab=Kf(),Cb=Gf();function jb(t=!1){let e=[Rb.default,Ib.default,Ob.default,Nb.default,Ab.default,Cb.default,zb.default,Eb.default,xb.default,kb.default,Pb.default];return t?e.push(Sb.default,Tb.default):e.push($b.default,bb.default),e.push(wb.default),e}Ia.default=jb});var Jf=S(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var oe=O(),Zb={message:({schemaCode:t})=>(0,oe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,oe._)`{format: ${t}}`},Db={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Zb,code(t,e){let{gen:r,data:o,$data:n,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;n?d():m();function d(){let _=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,oe._)`${_}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,oe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,oe._)`${g}.type || "string"`).assign(v,(0,oe._)`${g}.validate`),()=>r.assign(y,(0,oe._)`"string"`).assign(v,g)),t.fail$data((0,oe.or)(b(),$()));function b(){return c.strictSchema===!1?oe.nil:(0,oe._)`${i} && !${v}`}function $(){let z=u.$async?(0,oe._)`(${g}.async ? await ${v}(${o}) : ${v}(${o}))`:(0,oe._)`${v}(${o})`,k=(0,oe._)`(typeof ${v} == "function" ? ${z} : ${v}.test(${o}))`;return(0,oe._)`${v} && ${v} !== true && ${y} === ${e} && !${k}`}}function m(){let _=p.formats[s];if(!_){b();return}if(_===!0)return;let[g,y,v]=$(_);g===e&&t.pass(z());function b(){if(c.strictSchema===!1){p.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function $(k){let ge=k instanceof RegExp?(0,oe.regexpCode)(k):c.code.formats?(0,oe._)`${c.code.formats}${(0,oe.getProperty)(s)}`:void 0,Ee=r.scopeValue("formats",{key:s,ref:k,code:ge});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,oe._)`${Ee}.validate`]:["string",k,Ee]}function z(){if(typeof _=="object"&&!(_ instanceof RegExp)&&_.async){if(!u.$async)throw new Error("async format in sync schema");return(0,oe._)`await ${v}(${o})`}return typeof y=="function"?(0,oe._)`${v}(${o})`:(0,oe._)`${v}.test(${o})`}}}};Oa.default=Db});var Wf=S(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});var Mb=Jf(),qb=[Mb.default];Na.default=qb});var Yf=S(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.contentVocabulary=Bt.metadataVocabulary=void 0;Bt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Bt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Qf=S(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});var Lb=sf(),Ub=$f(),Fb=Bf(),Vb=Wf(),Xf=Yf(),Hb=[Lb.default,Ub.default,(0,Fb.default)(),Vb.default,Xf.metadataVocabulary,Xf.contentVocabulary];Aa.default=Hb});var tm=S(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.DiscrError=void 0;var em;(function(t){t.Tag="tag",t.Mapping="mapping"})(em||(gn.DiscrError=em={}))});var om=S(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});var Jt=O(),Ca=tm(),rm=Yo(),Kb=Lr(),Gb=D(),Bb={message:({params:{discrError:t,tagName:e}})=>t===Ca.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Jt._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Jb={keyword:"discriminator",type:"object",schemaType:"object",error:Bb,code(t){let{gen:e,data:r,schema:o,parentSchema:n,it:s}=t,{oneOf:i}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=o.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Jt._)`${r}${(0,Jt.getProperty)(a)}`);e.if((0,Jt._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Ca.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let m=d();e.if(!1);for(let _ in m)e.elseIf((0,Jt._)`${l} === ${_}`),e.assign(c,p(m[_]));e.else(),t.error(!1,{discrError:Ca.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(m){let _=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:m},_);return t.mergeEvaluated(g,Jt.Name),_}function d(){var m;let _={},g=v(n),y=!0;for(let z=0;z{Wb.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}});var Da=S((Y,Za)=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.MissingRefError=Y.ValidationError=Y.CodeGen=Y.Name=Y.nil=Y.stringify=Y.str=Y._=Y.KeywordCxt=Y.Ajv=void 0;var Yb=Qd(),Xb=Qf(),Qb=om(),sm=nm(),eT=["/properties"],yn="http://json-schema.org/draft-07/schema",Wt=class extends Yb.default{_addVocabularies(){super._addVocabularies(),Xb.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Qb.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(sm,eT):sm;this.addMetaSchema(e,yn,!1),this.refs["http://json-schema.org/schema"]=yn}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(yn)?yn:void 0)}};Y.Ajv=Wt;Za.exports=Y=Wt;Za.exports.Ajv=Wt;Object.defineProperty(Y,"__esModule",{value:!0});Y.default=Wt;var tT=qr();Object.defineProperty(Y,"KeywordCxt",{enumerable:!0,get:function(){return tT.KeywordCxt}});var Yt=O();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Yt._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Yt.str}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Yt.stringify}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Yt.nil}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Yt.Name}});Object.defineProperty(Y,"CodeGen",{enumerable:!0,get:function(){return Yt.CodeGen}});var rT=Jo();Object.defineProperty(Y,"ValidationError",{enumerable:!0,get:function(){return rT.default}});var oT=Lr();Object.defineProperty(Y,"MissingRefError",{enumerable:!0,get:function(){return oT.default}})});var fm=S(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.formatNames=Be.fastFormats=Be.fullFormats=void 0;function Ge(t,e){return{validate:t,compare:e}}Be.fullFormats={date:Ge(um,Ua),time:Ge(qa(!0),Fa),"date-time":Ge(im(!0),pm),"iso-time":Ge(qa(),lm),"iso-date-time":Ge(im(),dm),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:uT,"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:_T,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:lT,int32:{type:"number",validate:fT},int64:{type:"number",validate:mT},float:{type:"number",validate:cm},double:{type:"number",validate:cm},password:!0,binary:!0};Be.fastFormats={...Be.fullFormats,date:Ge(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ua),time:Ge(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Fa),"date-time":Ge(/^\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,pm),"iso-time":Ge(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,lm),"iso-date-time":Ge(/^\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,dm),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};Be.formatNames=Object.keys(Be.fullFormats);function nT(t){return t%4===0&&(t%100!==0||t%400===0)}var sT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,iT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function um(t){let e=sT.exec(t);if(!e)return!1;let r=+e[1],o=+e[2],n=+e[3];return o>=1&&o<=12&&n>=1&&n<=(o===2&&nT(r)?29:iT[o])}function Ua(t,e){if(t&&e)return t>e?1:t23||u>59||t&&!a)return!1;if(n<=23&&s<=59&&i<60)return!0;let p=s-u*c,d=n-l*c-(p<0?1:0);return(d===23||d===-1)&&(p===59||p===-1)&&i<61}}function Fa(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),o=new Date("2020-01-01T"+e).valueOf();if(r&&o)return r-o}function lm(t,e){if(!(t&&e))return;let r=Ma.exec(t),o=Ma.exec(e);if(r&&o)return t=r[1]+r[2]+r[3],e=o[1]+o[2]+o[3],t>e?1:t=pT}function mT(t){return Number.isInteger(t)}function cm(){return!0}var hT=/[^\\]\\Z/;function _T(t){if(hT.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var mm=S(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.formatLimitDefinition=void 0;var gT=Da(),qe=O(),ft=qe.operators,vn={formatMaximum:{okStr:"<=",ok:ft.LTE,fail:ft.GT},formatMinimum:{okStr:">=",ok:ft.GTE,fail:ft.LT},formatExclusiveMaximum:{okStr:"<",ok:ft.LT,fail:ft.GTE},formatExclusiveMinimum:{okStr:">",ok:ft.GT,fail:ft.LTE}},yT={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${vn[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${vn[t].okStr}, limit: ${e}}`};Xt.formatLimitDefinition={keyword:Object.keys(vn),type:"string",schemaType:"string",$data:!0,error:yT,code(t){let{gen:e,data:r,schemaCode:o,keyword:n,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new gT.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let d=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,qe._)`${d}[${c.schemaCode}]`);t.fail$data((0,qe.or)((0,qe._)`typeof ${m} != "object"`,(0,qe._)`${m} instanceof RegExp`,(0,qe._)`typeof ${m}.compare != "function"`,p(m)))}function u(){let d=c.schema,m=a.formats[d];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${n}": format "${d}" does not define "compare" function`);let _=e.scopeValue("formats",{key:d,ref:m,code:i.code.formats?(0,qe._)`${i.code.formats}${(0,qe.getProperty)(d)}`:void 0});t.fail$data(p(_))}function p(d){return(0,qe._)`${d}.compare(${r}, ${o}) ${vn[n].fail} 0`}},dependencies:["format"]};var vT=t=>(t.addKeyword(Xt.formatLimitDefinition),t);Xt.default=vT});var ym=S((to,gm)=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});var Qt=fm(),$T=mm(),Va=O(),hm=new Va.Name("fullFormats"),ST=new Va.Name("fastFormats"),Ha=(t,e={keywords:!0})=>{if(Array.isArray(e))return _m(t,e,Qt.fullFormats,hm),t;let[r,o]=e.mode==="fast"?[Qt.fastFormats,ST]:[Qt.fullFormats,hm],n=e.formats||Qt.formatNames;return _m(t,n,r,o),e.keywords&&(0,$T.default)(t),t};Ha.get=(t,e="full")=>{let o=(e==="fast"?Qt.fastFormats:Qt.fullFormats)[t];if(!o)throw new Error(`Unknown format "${t}"`);return o};function _m(t,e,r,o){var n,s;(n=(s=t.opts.code).formats)!==null&&n!==void 0||(s.formats=(0,Va._)`require("ajv-formats/dist/formats").${o}`);for(let i of e)t.addFormat(i,r[i])}gm.exports=to=Ha;Object.defineProperty(to,"__esModule",{value:!0});to.default=Ha});var BT=Object.freeze({status:"aborted"});function h(t,e,r){function o(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;o(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var We=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},oo={};function ke(t){return t&&Object.assign(oo,t),oo}var L={};ic(L,{BIGINT_FORMAT_RANGES:()=>uc,Class:()=>qn,NUMBER_FORMAT_RANGES:()=>Bn,aborted:()=>ht,allowsEval:()=>Hn,assert:()=>bh,assertEqual:()=>yh,assertIs:()=>$h,assertNever:()=>Sh,assertNotEqual:()=>vh,assignProp:()=>Vn,cached:()=>rr,captureStackTrace:()=>so,cleanEnum:()=>Ch,cleanRegex:()=>nr,clone:()=>Ue,createTransparentProxy:()=>kh,defineLazy:()=>H,esc:()=>mt,escapeRegex:()=>rt,extend:()=>Ih,finalizeIssue:()=>Ce,floatSafeRemainder:()=>Fn,getElementAtPath:()=>Th,getEnumValues:()=>Ln,getLengthableOrigin:()=>sr,getParsedType:()=>Eh,getSizableOrigin:()=>lc,isObject:()=>Pt,isPlainObject:()=>Rt,issue:()=>Jn,joinValues:()=>no,jsonStringifyReplacer:()=>Un,merge:()=>Oh,normalizeParams:()=>E,nullish:()=>or,numKeys:()=>zh,omit:()=>Rh,optionalKeys:()=>Gn,partial:()=>Nh,pick:()=>Ph,prefixIssues:()=>Fe,primitiveTypes:()=>cc,promiseAllObject:()=>wh,propertyKeyTypes:()=>Kn,randomString:()=>xh,required:()=>Ah,stringifyPrimitive:()=>io,unwrapMessage:()=>tr});function yh(t){return t}function vh(t){return t}function $h(t){}function Sh(t){throw new Error}function bh(t){}function Ln(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,n])=>e.indexOf(+o)===-1).map(([o,n])=>n)}function no(t,e="|"){return t.map(r=>io(r)).join(e)}function Un(t,e){return typeof e=="bigint"?e.toString():e}function rr(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function or(t){return t==null}function nr(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Fn(t,e){let r=(t.toString().split(".")[1]||"").length,o=(e.toString().split(".")[1]||"").length,n=r>o?r:o,s=Number.parseInt(t.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return s%i/10**n}function H(t,e,r){Object.defineProperty(t,e,{get(){{let n=r();return t[e]=n,n}throw new Error("cached value already set")},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Vn(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Th(t,e){return e?e.reduce((r,o)=>r?.[o],t):t}function wh(t){let e=Object.keys(t),r=e.map(o=>t[o]);return Promise.all(r).then(o=>{let n={};for(let s=0;s{};function Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Hn=rr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Rt(t){if(Pt(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Pt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function zh(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Eh=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Kn=new Set(["string","number","symbol"]),cc=new Set(["string","number","bigint","boolean","symbol","undefined"]);function rt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ue(t,e,r){let o=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(o._zod.parent=t),o}function E(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function kh(t){let e;return new Proxy({},{get(r,o,n){return e??(e=t()),Reflect.get(e,o,n)},set(r,o,n,s){return e??(e=t()),Reflect.set(e,o,n,s)},has(r,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(r,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(r,o,n){return e??(e=t()),Reflect.defineProperty(e,o,n)}})}function io(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Gn(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Bn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},uc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Ph(t,e){let r={},o=t._zod.def;for(let n in e){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=o.shape[n])}return Ue(t,{...t._zod.def,shape:r,checks:[]})}function Rh(t,e){let r={...t._zod.def.shape},o=t._zod.def;for(let n in e){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return Ue(t,{...t._zod.def,shape:r,checks:[]})}function Ih(t,e){if(!Rt(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let o={...t._zod.def.shape,...e};return Vn(this,"shape",o),o},checks:[]};return Ue(t,r)}function Oh(t,e){return Ue(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Vn(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Nh(t,e,r){let o=e._zod.def.shape,n={...o};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=t?new t({type:"optional",innerType:o[s]}):o[s])}else for(let s in o)n[s]=t?new t({type:"optional",innerType:o[s]}):o[s];return Ue(e,{...e._zod.def,shape:n,checks:[]})}function Ah(t,e,r){let o=e._zod.def.shape,n={...o};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=new t({type:"nonoptional",innerType:o[s]}))}else for(let s in o)n[s]=new t({type:"nonoptional",innerType:o[s]});return Ue(e,{...e._zod.def,shape:n,checks:[]})}function ht(t,e=0){for(let r=e;r{var o;return(o=r).path??(o.path=[]),r.path.unshift(t),r})}function tr(t){return typeof t=="string"?t:t?.message}function Ce(t,e,r){let o={...t,path:t.path??[]};if(!t.message){let n=tr(t.inst?._zod.def?.error?.(t))??tr(e?.error?.(t))??tr(r.customError?.(t))??tr(r.localeError?.(t))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,e?.reportInput||delete o.input,o}function lc(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function sr(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Jn(...t){let[e,r,o]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:o}:{...e}}function Ch(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var qn=class{constructor(...e){}};var pc=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Un,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ao=h("$ZodError",pc),Wn=h("$ZodError",pc,{Parent:Error});function dc(t,e=r=>r.message){let r={},o=[];for(let n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):o.push(e(n));return{formErrors:o,fieldErrors:r}}function fc(t,e){let r=e||function(s){return s.message},o={_errors:[]},n=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)o._errors.push(r(i));else{let a=o,c=0;for(;c(e,r,o,n)=>{let s=o?Object.assign(o,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new We;if(i.issues.length){let a=new(n?.Err??t)(i.issues.map(c=>Ce(c,s,ke())));throw so(a,n?.callee),a}return i.value};var hc=t=>async(e,r,o,n)=>{let s=o?Object.assign(o,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(n?.Err??t)(i.issues.map(c=>Ce(c,s,ke())));throw so(a,n?.callee),a}return i.value};var Yn=t=>(e,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new We;return s.issues.length?{success:!1,error:new(t??ao)(s.issues.map(i=>Ce(i,n,ke())))}:{success:!0,data:s.value}},ir=Yn(Wn),Xn=t=>async(e,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Ce(i,n,ke())))}:{success:!0,data:s.value}},co=Xn(Wn);var _c=/^[cC][^\s-]{8,}$/,gc=/^[0-9a-z]+$/,yc=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vc=/^[0-9a-vA-V]{20}$/,$c=/^[A-Za-z0-9]{27}$/,Sc=/^[a-zA-Z0-9_-]{21}$/,bc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Tc=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Qn=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var wc=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Zh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function xc(){return new RegExp(Zh,"u")}var zc=/^(?:(?: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])$/,Ec=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,kc=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Pc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Rc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,es=/^[A-Za-z0-9_-]*$/,Ic=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Oc=/^\+(?:[0-9]){6,14}[0-9]$/,Nc="(?:(?:\\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])))",Ac=new RegExp(`^${Nc}$`);function Cc(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function jc(t){return new RegExp(`^${Cc(t)}$`)}function Zc(t){let e=Cc({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let o=`${e}(?:${r.join("|")})`;return new RegExp(`^${Nc}T(?:${o})$`)}var Dc=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Mc=/^\d+$/,qc=/^-?\d+(?:\.\d+)?/i,Lc=/true|false/i,Uc=/null/i;var Fc=/^[^A-Z]*$/,Vc=/^[^a-z]*$/;var fe=h("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Hc={number:"number",bigint:"bigint",object:"date"},rs=h("$ZodCheckLessThan",(t,e)=>{fe.init(t,e);let r=Hc[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?o.value<=e.value:o.value{fe.init(t,e);let r=Hc[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:r,code:"too_small",minimum:e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Kc=h("$ZodCheckMultipleOf",(t,e)=>{fe.init(t,e),t._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Fn(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Gc=h("$ZodCheckNumberFormat",(t,e)=>{fe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),o=r?"int":"number",[n,s]=Bn[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=n,a.maximum=s,r&&(a.pattern=Mc)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,continue:!e.abort});return}}as&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var Bc=h("$ZodCheckMaxLength",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!or(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let n=o.value;if(n.length<=e.maximum)return;let i=sr(n);o.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Jc=h("$ZodCheckMinLength",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!or(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let n=o.value;if(n.length>=e.minimum)return;let i=sr(n);o.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Wc=h("$ZodCheckLengthEquals",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!or(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=o=>{let n=o.value,s=n.length;if(s===e.length)return;let i=sr(n),a=s>e.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),ar=h("$ZodCheckStringFormat",(t,e)=>{var r,o;fe.init(t,e),t._zod.onattach.push(n=>{let s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),Yc=h("$ZodCheckRegex",(t,e)=>{ar.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Xc=h("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Fc),ar.init(t,e)}),Qc=h("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Vc),ar.init(t,e)}),eu=h("$ZodCheckIncludes",(t,e)=>{fe.init(t,e);let r=rt(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=o,t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),tu=h("$ZodCheckStartsWith",(t,e)=>{fe.init(t,e);let r=new RegExp(`^${rt(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),ru=h("$ZodCheckEndsWith",(t,e)=>{fe.init(t,e);let r=new RegExp(`.*${rt(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});var ou=h("$ZodCheckOverwrite",(t,e)=>{fe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var uo=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let o=e.split(` -`).filter(i=>i),n=Math.min(...o.map(i=>i.length-i.trimStart().length)),s=o.map(i=>i.slice(n)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,n=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,n.join(` -`))}};var su={major:4,minor:0,patch:0};var K=h("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=su;let o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let n of o)for(let s of n._zod.onattach)s(t);if(o.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let n=(s,i,a)=>{let c=ht(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,d=u._zod.check(s);if(d instanceof Promise&&a?.async===!1)throw new We;if(l||d instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await d,s.issues.length!==p&&(c||(c=ht(s,p)))});else{if(s.issues.length===p)continue;c||(c=ht(s,p))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new We;return a.then(c=>n(c,o,i))}return n(a,o,i)}}t["~standard"]={validate:n=>{try{let s=ir(t,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return co(t,n).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),po=h("$ZodString",(t,e)=>{K.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Dc(t._zod.bag),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),B=h("$ZodStringFormat",(t,e)=>{ar.init(t,e),po.init(t,e)}),hu=h("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Tc),B.init(t,e)}),_u=h("$ZodUUID",(t,e)=>{if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Qn(o))}else e.pattern??(e.pattern=Qn());B.init(t,e)}),gu=h("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=wc),B.init(t,e)}),yu=h("$ZodURL",(t,e)=>{B.init(t,e),t._zod.check=r=>{try{let o=r.value,n=new URL(o),s=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Ic.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!o.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),vu=h("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=xc()),B.init(t,e)}),$u=h("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Sc),B.init(t,e)}),Su=h("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=_c),B.init(t,e)}),bu=h("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=gc),B.init(t,e)}),Tu=h("$ZodULID",(t,e)=>{e.pattern??(e.pattern=yc),B.init(t,e)}),wu=h("$ZodXID",(t,e)=>{e.pattern??(e.pattern=vc),B.init(t,e)}),xu=h("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=$c),B.init(t,e)}),zu=h("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Zc(e)),B.init(t,e)}),Eu=h("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ac),B.init(t,e)}),ku=h("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=jc(e)),B.init(t,e)}),Pu=h("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=bc),B.init(t,e)}),Ru=h("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=zc),B.init(t,e),t._zod.onattach.push(r=>{let o=r._zod.bag;o.format="ipv4"})}),Iu=h("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ec),B.init(t,e),t._zod.onattach.push(r=>{let o=r._zod.bag;o.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Ou=h("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=kc),B.init(t,e)}),Nu=h("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Pc),B.init(t,e),t._zod.check=r=>{let[o,n]=r.value.split("/");try{if(!n)throw new Error;let s=Number(n);if(`${s}`!==n)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Au(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Cu=h("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Rc),B.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Au(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Dh(t){if(!es.test(t))return!1;let e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Au(r)}var ju=h("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=es),B.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Dh(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Zu=h("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Oc),B.init(t,e)});function Mh(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}var Du=h("$ZodJWT",(t,e)=>{B.init(t,e),t._zod.check=r=>{Mh(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var ss=h("$ZodNumber",(t,e)=>{K.init(t,e),t._zod.pattern=t._zod.bag.pattern??qc,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),Mu=h("$ZodNumber",(t,e)=>{Gc.init(t,e),ss.init(t,e)}),qu=h("$ZodBoolean",(t,e)=>{K.init(t,e),t._zod.pattern=Lc,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}});var Lu=h("$ZodNull",(t,e)=>{K.init(t,e),t._zod.pattern=Uc,t._zod.values=new Set([null]),t._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}});var Uu=h("$ZodUnknown",(t,e)=>{K.init(t,e),t._zod.parse=r=>r}),Fu=h("$ZodNever",(t,e)=>{K.init(t,e),t._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function iu(t,e,r){t.issues.length&&e.issues.push(...Fe(r,t.issues)),e.value[r]=t.value}var Vu=h("$ZodArray",(t,e)=>{K.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);let s=[];for(let i=0;iiu(l,r,i))):iu(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function lo(t,e,r){t.issues.length&&e.issues.push(...Fe(r,t.issues)),e.value[r]=t.value}function au(t,e,r,o){t.issues.length?o[r]===void 0?r in o?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Fe(r,t.issues)):t.value===void 0?r in o&&(e.value[r]=void 0):e.value[r]=t.value}var Hu=h("$ZodObject",(t,e)=>{K.init(t,e);let r=rr(()=>{let p=Object.keys(e.shape);for(let m of p)if(!(e.shape[m]instanceof K))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let d=Gn(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(d)}});H(t._zod,"propValues",()=>{let p=e.shape,d={};for(let m in p){let _=p[m]._zod;if(_.values){d[m]??(d[m]=new Set);for(let g of _.values)d[m].add(g)}}return d});let o=p=>{let d=new uo(["shape","payload","ctx"]),m=r.value,_=b=>{let $=mt(b);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};d.write("const input = payload.value;");let g=Object.create(null),y=0;for(let b of m.keys)g[b]=`key_${y++}`;d.write("const newResult = {}");for(let b of m.keys)if(m.optionalKeys.has(b)){let $=g[b];d.write(`const ${$} = ${_(b)};`);let z=mt(b);d.write(` - if (${$}.issues.length) { - if (input[${z}] === undefined) { - if (${z} in input) { - newResult[${z}] = undefined; - } - } else { - payload.issues = payload.issues.concat( - ${$}.issues.map((iss) => ({ - ...iss, - path: iss.path ? [${z}, ...iss.path] : [${z}], - })) - ); +var Ig=Object.defineProperty;var $s=(e,t)=>{for(var r in t)Ig(e,r,{get:t[r],enumerable:!0})};var Pg=Object.create,Zo=Object.defineProperty,kg=Object.getOwnPropertyDescriptor,Og=Object.getOwnPropertyNames,jg=Object.getPrototypeOf,Ng=Object.prototype.hasOwnProperty,L=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Rl=(e,t)=>{let r={};for(var n in e)Zo(r,n,{get:e[n],enumerable:!0});return t&&Zo(r,Symbol.toStringTag,{value:"Module"}),r},xg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var o=Og(t),i=0,a=o.length,c;it[s]).bind(null,c),enumerable:!(n=kg(t,c))||n.enumerable});return e},Fo=(e,t,r)=>(r=e!=null?Pg(jg(e)):{},xg(t||!e||!e.__esModule?Zo(r,"default",{value:e,enumerable:!0}):r,e));var Cg=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),wl=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Ag=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),qg=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function Tl(e){return typeof e=="string"&&wl.has(e.replace(/#$/,""))}function El(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(Cg.has(r))return"2020-12";if(wl.has(r))return"2019-09";if(Ag.has(r)||qg.has(r))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var zs=Object.freeze({status:"aborted"});function q(e,t,r){function n(c,s){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:s,constr:a,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,s);let l=a.prototype,m=Object.keys(l);for(let h=0;hr?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var ft=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Tr=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},Ho={};function We(e){return e&&Object.assign(Ho,e),Ho}var J={};$s(J,{BIGINT_FORMAT_RANGES:()=>Ol,Class:()=>ws,NUMBER_FORMAT_RANGES:()=>Os,aborted:()=>Ct,allowsEval:()=>Is,assert:()=>Vg,assertEqual:()=>Mg,assertIs:()=>Lg,assertNever:()=>Dg,assertNotEqual:()=>Ug,assignProp:()=>jt,base64ToUint8Array:()=>Nl,base64urlToUint8Array:()=>iv,cached:()=>Ir,captureStackTrace:()=>Bo,cleanEnum:()=>ov,cleanRegex:()=>On,clone:()=>it,cloneDef:()=>Fg,createTransparentProxy:()=>Wg,defineLazy:()=>Se,esc:()=>Jo,escapeRegex:()=>ht,extend:()=>Qg,finalizeIssue:()=>ct,floatSafeRemainder:()=>Ts,getElementAtPath:()=>Hg,getEnumValues:()=>Pn,getLengthableOrigin:()=>jn,getParsedType:()=>Gg,getSizableOrigin:()=>jl,hexToUint8Array:()=>sv,isObject:()=>nr,isPlainObject:()=>xt,issue:()=>Pr,joinValues:()=>ce,jsonStringifyReplacer:()=>Er,merge:()=>tv,mergeDefs:()=>Nt,normalizeParams:()=>re,nullish:()=>kn,numKeys:()=>Kg,objectClone:()=>Zg,omit:()=>Xg,optionalKeys:()=>ks,partial:()=>rv,pick:()=>Yg,prefixIssues:()=>yt,primitiveTypes:()=>kl,promiseAllObject:()=>Jg,propertyKeyTypes:()=>Ps,randomString:()=>Bg,required:()=>nv,safeExtend:()=>ev,shallowClone:()=>Pl,slugify:()=>Es,stringifyPrimitive:()=>ue,uint8ArrayToBase64:()=>xl,uint8ArrayToBase64url:()=>av,uint8ArrayToHex:()=>cv,unwrapMessage:()=>In});function Mg(e){return e}function Ug(e){return e}function Lg(e){}function Dg(e){throw new Error("Unexpected value in exhaustive check")}function Vg(e){}function Pn(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ce(e,t="|"){return e.map(r=>ue(r)).join(t)}function Er(e,t){return typeof t=="bigint"?t.toString():t}function Ir(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function kn(e){return e==null}function On(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ts(e,t){let r=(e.toString().split(".")[1]||"").length,n=t.toString(),o=(n.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(n)){let s=n.match(/\d?e-(\d?)/);s?.[1]&&(o=Number.parseInt(s[1]))}let i=r>o?r:o,a=Number.parseInt(e.toFixed(i).replace(".","")),c=Number.parseInt(t.toFixed(i).replace(".",""));return a%c/10**i}var Il=Symbol("evaluating");function Se(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Il)return n===void 0&&(n=Il,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Zg(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function jt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Nt(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Fg(e){return Nt(e._zod.def)}function Hg(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Jg(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i{};function nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Is=Ir(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function xt(e){if(nr(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(nr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Pl(e){return xt(e)?{...e}:Array.isArray(e)?[...e]:e}function Kg(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Gg=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Ps=new Set(["string","number","symbol"]),kl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ht(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function it(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function re(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Wg(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ue(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function ks(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Os={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ol={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Yg(e,t){let r=e._zod.def,n=Nt(e._zod.def,{get shape(){let o={};for(let i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(o[i]=r.shape[i])}return jt(this,"shape",o),o},checks:[]});return it(e,n)}function Xg(e,t){let r=e._zod.def,n=Nt(e._zod.def,{get shape(){let o={...e._zod.def.shape};for(let i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete o[i]}return jt(this,"shape",o),o},checks:[]});return it(e,n)}function Qg(e,t){if(!xt(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let o=Nt(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return jt(this,"shape",i),i},checks:[]});return it(e,o)}function ev(e,t){if(!xt(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return jt(this,"shape",n),n},checks:e._zod.def.checks};return it(e,r)}function tv(e,t){let r=Nt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return jt(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return it(e,r)}function rv(e,t,r){let n=Nt(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let a in r){if(!(a in o))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=e?new e({type:"optional",innerType:o[a]}):o[a])}else for(let a in o)i[a]=e?new e({type:"optional",innerType:o[a]}):o[a];return jt(this,"shape",i),i},checks:[]});return it(t,n)}function nv(e,t,r){let n=Nt(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new e({type:"nonoptional",innerType:o[a]}))}else for(let a in o)i[a]=new e({type:"nonoptional",innerType:o[a]});return jt(this,"shape",i),i},checks:[]});return it(t,n)}function Ct(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function In(e){return typeof e=="string"?e:e?.message}function ct(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=In(e.inst?._zod.def?.error?.(e))??In(t?.error?.(e))??In(r.customError?.(e))??In(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function jl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function jn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Pr(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function ov(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Nl(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;nt.toString(16).padStart(2,"0")).join("")}var ws=class{constructor(...t){}};var Cl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Er,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ko=q("$ZodError",Cl),js=q("$ZodError",Cl,{Parent:Error});function Ns(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function xs(e,t=r=>r.message){let r={_errors:[]},n=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)r._errors.push(t(i));else{let a=r,c=0;for(;c(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new ft;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map(s=>ct(s,i,We())));throw Bo(c,o?.callee),c}return a.value};var Wo=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(o?.Err??e)(a.issues.map(s=>ct(s,i,We())));throw Bo(c,o?.callee),c}return a.value};var Nn=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ft;return i.issues.length?{success:!1,error:new(e??Ko)(i.issues.map(a=>ct(a,o,We())))}:{success:!0,data:i.value}},Al=Nn(js),xn=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>ct(a,o,We())))}:{success:!0,data:i.value}},ql=xn(js),Ml=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Go(e)(t,r,o)};var Ul=e=>(t,r,n)=>Go(e)(t,r,n);var Ll=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Wo(e)(t,r,o)};var Dl=e=>async(t,r,n)=>Wo(e)(t,r,n);var Vl=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Nn(e)(t,r,o)};var Zl=e=>(t,r,n)=>Nn(e)(t,r,n);var Fl=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return xn(e)(t,r,o)};var Hl=e=>async(t,r,n)=>xn(e)(t,r,n);var Jl=/^[cC][^\s-]{8,}$/,Bl=/^[0-9a-z]+$/,Kl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gl=/^[0-9a-vA-V]{20}$/,Wl=/^[A-Za-z0-9]{27}$/,Yl=/^[a-zA-Z0-9_-]{21}$/,Xl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ql=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Cs=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var ed=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var lv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function td(){return new RegExp(lv,"u")}var rd=/^(?:(?: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])$/,nd=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var od=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,id=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ad=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,As=/^[A-Za-z0-9_-]*$/;var sd=/^\+(?:[0-9]){6,14}[0-9]$/,cd="(?:(?:\\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])))",ud=new RegExp(`^${cd}$`);function ld(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function dd(e){return new RegExp(`^${ld(e)}$`)}function md(e){let t=ld({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${cd}T(?:${n})$`)}var pd=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},fd=/^-?\d+n?$/,hd=/^-?\d+$/,gd=/^-?\d+(?:\.\d+)?/,vd=/^(?:true|false)$/i,_d=/^null$/i;var Sd=/^[^A-Z]*$/,yd=/^[^a-z]*$/;var Ve=q("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),bd={number:"number",bigint:"bigint",object:"date"},qs=q("$ZodCheckLessThan",(e,t)=>{Ve.init(e,t);let r=bd[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?n.value<=t.value:n.value{Ve.init(e,t);let r=bd[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$d=q("$ZodCheckMultipleOf",(e,t)=>{Ve.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Ts(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),zd=q("$ZodCheckNumberFormat",(e,t)=>{Ve.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Os[t.format];e._zod.onattach.push(a=>{let c=a._zod.bag;c.format=t.format,c.minimum=o,c.maximum=i,r&&(c.pattern=hd)}),e._zod.check=a=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}ci&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:e})}});var Rd=q("$ZodCheckMaxLength",(e,t)=>{var r;Ve.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!kn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{let o=n.value;if(o.length<=t.maximum)return;let a=jn(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),wd=q("$ZodCheckMinLength",(e,t)=>{var r;Ve.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!kn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let a=jn(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Td=q("$ZodCheckLengthEquals",(e,t)=>{var r;Ve.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!kn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let a=jn(o),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),An=q("$ZodCheckStringFormat",(e,t)=>{var r,n;Ve.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Ed=q("$ZodCheckRegex",(e,t)=>{An.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Id=q("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Sd),An.init(e,t)}),Pd=q("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yd),An.init(e,t)}),kd=q("$ZodCheckIncludes",(e,t)=>{Ve.init(e,t);let r=ht(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Od=q("$ZodCheckStartsWith",(e,t)=>{Ve.init(e,t);let r=new RegExp(`^${ht(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),jd=q("$ZodCheckEndsWith",(e,t)=>{Ve.init(e,t);let r=new RegExp(`.*${ht(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Nd=q("$ZodCheckOverwrite",(e,t)=>{Ve.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Yo=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(` +`).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(` +`))}};var Cd={major:4,minor:2,patch:0};var ye=q("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cd;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,c,s)=>{let l=Ct(a),m;for(let h of c){if(h._zod.def.when){if(!h._zod.def.when(a))continue}else if(l)continue;let z=a.issues.length,R=h._zod.check(a);if(R instanceof Promise&&s?.async===!1)throw new ft;if(m||R instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await R,a.issues.length!==z&&(l||(l=Ct(a,z)))});else{if(a.issues.length===z)continue;l||(l=Ct(a,z))}}return m?m.then(()=>a):a},i=(a,c,s)=>{if(Ct(a))return a.aborted=!0,a;let l=o(c,n,s);if(l instanceof Promise){if(s.async===!1)throw new ft;return l.then(m=>e._zod.parse(m,s))}return e._zod.parse(l,s)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let l=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(m=>i(m,a,c)):i(l,a,c)}let s=e._zod.parse(a,c);if(s instanceof Promise){if(c.async===!1)throw new ft;return s.then(l=>o(l,n,c))}return o(s,n,c)}}e["~standard"]={validate:o=>{try{let i=Al(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return ql(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),qn=q("$ZodString",(e,t)=>{ye.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pd(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),we=q("$ZodStringFormat",(e,t)=>{An.init(e,t),qn.init(e,t)}),Fd=q("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ql),we.init(e,t)}),Hd=q("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Cs(n))}else t.pattern??(t.pattern=Cs());we.init(e,t)}),Jd=q("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ed),we.init(e,t)}),Bd=q("$ZodURL",(e,t)=>{we.init(e,t),e._zod.check=r=>{try{let n=r.value.trim(),o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Kd=q("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=td()),we.init(e,t)}),Gd=q("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Yl),we.init(e,t)}),Wd=q("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Jl),we.init(e,t)}),Yd=q("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Bl),we.init(e,t)}),Xd=q("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Kl),we.init(e,t)}),Qd=q("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Gl),we.init(e,t)}),em=q("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Wl),we.init(e,t)}),tm=q("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=md(t)),we.init(e,t)}),rm=q("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ud),we.init(e,t)}),nm=q("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=dd(t)),we.init(e,t)}),om=q("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Xl),we.init(e,t)}),im=q("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=rd),we.init(e,t),e._zod.bag.format="ipv4"}),am=q("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=nd),we.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var sm=q("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=od),we.init(e,t)}),cm=q("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=id),we.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function um(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var lm=q("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ad),we.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{um(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function dv(e){if(!As.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return um(r)}var dm=q("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=As),we.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{dv(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),mm=q("$ZodE164",(e,t)=>{t.pattern??(t.pattern=sd),we.init(e,t)});function mv(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var pm=q("$ZodJWT",(e,t)=>{we.init(e,t),e._zod.check=r=>{mv(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Ls=q("$ZodNumber",(e,t)=>{ye.init(e,t),e._zod.pattern=e._zod.bag.pattern??gd,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),fm=q("$ZodNumberFormat",(e,t)=>{zd.init(e,t),Ls.init(e,t)}),Ds=q("$ZodBoolean",(e,t)=>{ye.init(e,t),e._zod.pattern=vd,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),hm=q("$ZodBigInt",(e,t)=>{ye.init(e,t),e._zod.pattern=fd,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var gm=q("$ZodNull",(e,t)=>{ye.init(e,t),e._zod.pattern=_d,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),vm=q("$ZodAny",(e,t)=>{ye.init(e,t),e._zod.parse=r=>r}),_m=q("$ZodUnknown",(e,t)=>{ye.init(e,t),e._zod.parse=r=>r}),Sm=q("$ZodNever",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var ym=q("$ZodDate",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});function Ad(e,t,r){e.issues.length&&t.issues.push(...yt(r,e.issues)),t.value[r]=e.value}var bm=q("$ZodArray",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let a=0;aAd(l,r,a))):Ad(s,r,a)}return i.length?Promise.all(i).then(()=>r):r}});function Qo(e,t,r,n){e.issues.length&&t.issues.push(...yt(r,e.issues)),e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function $m(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=ks(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function zm(e,t,r,n,o,i){let a=[],c=o.keySet,s=o.catchall._zod,l=s.def.type;for(let m in t){if(c.has(m))continue;if(l==="never"){a.push(m);continue}let h=s.run({value:t[m],issues:[]},n);h instanceof Promise?e.push(h.then(z=>Qo(z,r,m,t))):Qo(h,r,m,t)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}var pv=q("$ZodObject",(e,t)=>{if(ye.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let s={...c};return Object.defineProperty(t,"shape",{value:s}),s}})}let n=Ir(()=>$m(t));Se(e._zod,"propValues",()=>{let c=t.shape,s={};for(let l in c){let m=c[l]._zod;if(m.values){s[l]??(s[l]=new Set);for(let h of m.values)s[l].add(h)}}return s});let o=nr,i=t.catchall,a;e._zod.parse=(c,s)=>{a??(a=n.value);let l=c.value;if(!o(l))return c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c;c.value={};let m=[],h=a.shape;for(let z of a.keys){let v=h[z]._zod.run({value:l[z],issues:[]},s);v instanceof Promise?m.push(v.then(b=>Qo(b,c,z,l))):Qo(v,c,z,l)}return i?zm(m,l,c,s,n.value,e):m.length?Promise.all(m).then(()=>c):c}}),Rm=q("$ZodObjectJIT",(e,t)=>{pv.init(e,t);let r=e._zod.parse,n=Ir(()=>$m(t)),o=z=>{let R=new Yo(["shape","payload","ctx"]),v=n.value,b=p=>{let S=Jo(p);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};R.write("const input = payload.value;");let g=Object.create(null),d=0;for(let p of v.keys)g[p]=`key_${d++}`;R.write("const newResult = {};");for(let p of v.keys){let S=g[p],w=Jo(p);R.write(`const ${S} = ${b(p)};`),R.write(` + if (${S}.issues.length) { + payload.issues = payload.issues.concat(${S}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${w}, ...iss.path] : [${w}] + }))); + } + + + if (${S}.value === undefined) { + if (${w} in input) { + newResult[${w}] = undefined; } - } else if (${$}.value === undefined) { - if (${z} in input) newResult[${z}] = undefined; } else { - newResult[${z}] = ${$}.value; + newResult[${w}] = ${S}.value; } - `)}else{let $=g[b];d.write(`const ${$} = ${_(b)};`),d.write(` - if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${mt(b)}, ...iss.path] : [${mt(b)}] - })));`),d.write(`newResult[${mt(b)}] = ${$}.value`)}d.write("payload.value = newResult;"),d.write("return payload;");let v=d.compile();return(b,$)=>v(p,b,$)},n,s=Pt,i=!oo.jitless,c=i&&Hn.value,l=e.catchall,u;t._zod.parse=(p,d)=>{u??(u=r.value);let m=p.value;if(!s(m))return p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p;let _=[];if(i&&c&&d?.async===!1&&d.jitless!==!0)n||(n=o(e.shape)),p=n(p,d);else{p.value={};let $=u.shape;for(let z of u.keys){let k=$[z],ge=k._zod.run({value:m[z],issues:[]},d),Ee=k._zod.optin==="optional"&&k._zod.optout==="optional";ge instanceof Promise?_.push(ge.then(kt=>Ee?au(kt,p,z,m):lo(kt,p,z))):Ee?au(ge,p,z,m):lo(ge,p,z)}}if(!l)return _.length?Promise.all(_).then(()=>p):p;let g=[],y=u.keySet,v=l._zod,b=v.def.type;for(let $ of Object.keys(m)){if(y.has($))continue;if(b==="never"){g.push($);continue}let z=v.run({value:m[$],issues:[]},d);z instanceof Promise?_.push(z.then(k=>lo(k,p,$))):lo(z,p,$)}return g.length&&p.issues.push({code:"unrecognized_keys",keys:g,input:m,inst:t}),_.length?Promise.all(_).then(()=>p):p}});function cu(t,e,r,o){for(let n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>Ce(s,o,ke())))}),e}var is=h("$ZodUnion",(t,e)=>{K.init(t,e),H(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),H(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),H(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),H(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>nr(o.source)).join("|")})$`)}}),t._zod.parse=(r,o)=>{let n=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},o);if(a instanceof Promise)s.push(a),n=!0;else{if(a.issues.length===0)return a;s.push(a)}}return n?Promise.all(s).then(i=>cu(i,r,t,o)):cu(s,r,t,o)}}),Ku=h("$ZodDiscriminatedUnion",(t,e)=>{is.init(t,e);let r=t._zod.parse;H(t._zod,"propValues",()=>{let n={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){n[a]||(n[a]=new Set);for(let l of c)n[a].add(l)}}return n});let o=rr(()=>{let n=e.options,s=new Map;for(let i of n){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(n,s)=>{let i=n.value;if(!Pt(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),n;let a=o.value.get(i?.[e.discriminator]);return a?a._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),n)}}),Gu=h("$ZodIntersection",(t,e)=>{K.init(t,e),t._zod.parse=(r,o)=>{let n=r.value,s=e.left._zod.run({value:n,issues:[]},o),i=e.right._zod.run({value:n,issues:[]},o);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>uu(r,c,l)):uu(r,s,i)}});function ns(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Rt(t)&&Rt(e)){let r=Object.keys(e),o=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(let s of o){let i=ns(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o{K.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!Rt(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:n[c],issues:[]},o);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...Fe(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Fe(c,l.issues)),r.value[c]=l.value)}let a;for(let c in n)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(n)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},o);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Ce(l,o,ke())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:n[i],issues:[]},o);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...Fe(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Fe(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Ju=h("$ZodEnum",(t,e)=>{K.init(t,e);let r=Ln(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(o=>Kn.has(typeof o)).map(o=>typeof o=="string"?rt(o):o.toString()).join("|")})$`),t._zod.parse=(o,n)=>{let s=o.value;return t._zod.values.has(s)||o.issues.push({code:"invalid_value",values:r,input:s,inst:t}),o}}),Wu=h("$ZodLiteral",(t,e)=>{K.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rt(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}});var Yu=h("$ZodTransform",(t,e)=>{K.init(t,e),t._zod.parse=(r,o)=>{let n=e.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(i=>(r.value=i,r));if(n instanceof Promise)throw new We;return r.value=n,r}}),Xu=h("$ZodOptional",(t,e)=>{K.init(t,e),t._zod.optin="optional",t._zod.optout="optional",H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${nr(r.source)})?$`):void 0}),t._zod.parse=(r,o)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,o):r.value===void 0?r:e.innerType._zod.run(r,o)}),Qu=h("$ZodNullable",(t,e)=>{K.init(t,e),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${nr(r.source)}|null)$`):void 0}),H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,o)=>r.value===null?r:e.innerType._zod.run(r,o)}),el=h("$ZodDefault",(t,e)=>{K.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>lu(s,e)):lu(n,e)}});function lu(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var tl=h("$ZodPrefault",(t,e)=>{K.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,o))}),rl=h("$ZodNonOptional",(t,e)=>{K.init(t,e),H(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>pu(s,t)):pu(n,t)}});function pu(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var ol=h("$ZodCatch",(t,e)=>{K.init(t,e),t._zod.optin="optional",H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Ce(i,o,ke()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Ce(s,o,ke()))},input:r.value}),r.issues=[]),r)}});var nl=h("$ZodPipe",(t,e)=>{K.init(t,e),H(t._zod,"values",()=>e.in._zod.values),H(t._zod,"optin",()=>e.in._zod.optin),H(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,o)=>{let n=e.in._zod.run(r,o);return n instanceof Promise?n.then(s=>du(s,e,o)):du(n,e,o)}});function du(t,e,r){return ht(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var sl=h("$ZodReadonly",(t,e)=>{K.init(t,e),H(t._zod,"propValues",()=>e.innerType._zod.propValues),H(t._zod,"values",()=>e.innerType._zod.values),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(fu):fu(n)}});function fu(t){return t.value=Object.freeze(t.value),t}var il=h("$ZodCustom",(t,e)=>{fe.init(t,e),K.init(t,e),t._zod.parse=(r,o)=>r,t._zod.check=r=>{let o=r.value,n=e.fn(o);if(n instanceof Promise)return n.then(s=>mu(s,r,o,t));mu(n,r,o,t)}});function mu(t,e,r,o){if(!t){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),e.issues.push(Jn(n))}}var qh=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Lh=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(o){return t[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Invalid input: expected ${o.expected}, received ${qh(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${io(o.values[0])}`:`Invalid option: expected one of ${no(o.values,"|")}`;case"too_big":{let n=o.inclusive?"<=":"<",s=e(o.origin);return s?`Too big: expected ${o.origin??"value"} to have ${n}${o.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${n}${o.maximum.toString()}`}case"too_small":{let n=o.inclusive?">=":">",s=e(o.origin);return s?`Too small: expected ${o.origin} to have ${n}${o.minimum.toString()} ${s.unit}`:`Too small: expected ${o.origin} to be ${n}${o.minimum.toString()}`}case"invalid_format":{let n=o;return n.format==="starts_with"?`Invalid string: must start with "${n.prefix}"`:n.format==="ends_with"?`Invalid string: must end with "${n.suffix}"`:n.format==="includes"?`Invalid string: must include "${n.includes}"`:n.format==="regex"?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${r[n.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${no(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function al(){return{localeError:Lh()}}var as=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let o=r[0];if(this._map.set(e,o),o&&typeof o=="object"&&"id"in o){if(this._idmap.has(o.id))throw new Error(`ID ${o.id} already exists in the registry`);this._idmap.set(o.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let o={...this.get(r)??{}};return delete o.id,{...o,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Uh(){return new as}var cr=Uh();function cl(t,e){return new t({type:"string",...E(e)})}function ul(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...E(e)})}function cs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...E(e)})}function ll(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...E(e)})}function pl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(e)})}function dl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(e)})}function fl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(e)})}function ml(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...E(e)})}function hl(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...E(e)})}function _l(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(e)})}function gl(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...E(e)})}function yl(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(e)})}function vl(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...E(e)})}function $l(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...E(e)})}function Sl(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(e)})}function bl(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(e)})}function Tl(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(e)})}function wl(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(e)})}function xl(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(e)})}function zl(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...E(e)})}function El(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...E(e)})}function kl(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...E(e)})}function Pl(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...E(e)})}function Rl(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(e)})}function Il(t,e){return new t({type:"string",format:"date",check:"string_format",...E(e)})}function Ol(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...E(e)})}function Nl(t,e){return new t({type:"string",format:"duration",check:"string_format",...E(e)})}function Al(t,e){return new t({type:"number",checks:[],...E(e)})}function Cl(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...E(e)})}function jl(t,e){return new t({type:"boolean",...E(e)})}function Zl(t,e){return new t({type:"null",...E(e)})}function Dl(t){return new t({type:"unknown"})}function Ml(t,e){return new t({type:"never",...E(e)})}function fo(t,e){return new rs({check:"less_than",...E(e),value:t,inclusive:!1})}function ur(t,e){return new rs({check:"less_than",...E(e),value:t,inclusive:!0})}function mo(t,e){return new os({check:"greater_than",...E(e),value:t,inclusive:!1})}function lr(t,e){return new os({check:"greater_than",...E(e),value:t,inclusive:!0})}function ho(t,e){return new Kc({check:"multiple_of",...E(e),value:t})}function _o(t,e){return new Bc({check:"max_length",...E(e),maximum:t})}function It(t,e){return new Jc({check:"min_length",...E(e),minimum:t})}function go(t,e){return new Wc({check:"length_equals",...E(e),length:t})}function us(t,e){return new Yc({check:"string_format",format:"regex",...E(e),pattern:t})}function ls(t){return new Xc({check:"string_format",format:"lowercase",...E(t)})}function ps(t){return new Qc({check:"string_format",format:"uppercase",...E(t)})}function ds(t,e){return new eu({check:"string_format",format:"includes",...E(e),includes:t})}function fs(t,e){return new tu({check:"string_format",format:"starts_with",...E(e),prefix:t})}function ms(t,e){return new ru({check:"string_format",format:"ends_with",...E(e),suffix:t})}function _t(t){return new ou({check:"overwrite",tx:t})}function hs(t){return _t(e=>e.normalize(t))}function _s(){return _t(t=>t.trim())}function gs(){return _t(t=>t.toLowerCase())}function ys(){return _t(t=>t.toUpperCase())}function ql(t,e,r){return new t({type:"array",element:e,...E(r)})}function Ll(t,e,r){let o=E(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function Ul(t,e,r){return new t({type:"custom",check:"custom",fn:e,...E(r)})}function yo(t){return!!t._zod}function ot(t,e){return yo(t)?ir(t,e):t.safeParse(e)}function vo(t){if(!t)return;let e;if(yo(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $o(t){if(yo(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let o=t.value;if(o!==void 0)return o}var dr={};ic(dr,{ZodISODate:()=>Vl,ZodISODateTime:()=>Fl,ZodISODuration:()=>Kl,ZodISOTime:()=>Hl,date:()=>$s,datetime:()=>vs,duration:()=>bs,time:()=>Ss});var Fl=h("ZodISODateTime",(t,e)=>{zu.init(t,e),X.init(t,e)});function vs(t){return Rl(Fl,t)}var Vl=h("ZodISODate",(t,e)=>{Eu.init(t,e),X.init(t,e)});function $s(t){return Il(Vl,t)}var Hl=h("ZodISOTime",(t,e)=>{ku.init(t,e),X.init(t,e)});function Ss(t){return Ol(Hl,t)}var Kl=h("ZodISODuration",(t,e)=>{Pu.init(t,e),X.init(t,e)});function bs(t){return Nl(Kl,t)}var Gl=(t,e)=>{ao.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>fc(t,r)},flatten:{value:r=>dc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Lw=h("ZodError",Gl),fr=h("ZodError",Gl,{Parent:Error});var Bl=mc(fr),Jl=hc(fr),Wl=Yn(fr),Yl=Xn(fr);var te=h("ZodType",(t,e)=>(K.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),t.clone=(r,o)=>Ue(t,r,o),t.brand=()=>t,t.register=((r,o)=>(r.add(t,o),t)),t.parse=(r,o)=>Bl(t,r,o,{callee:t.parse}),t.safeParse=(r,o)=>Wl(t,r,o),t.parseAsync=async(r,o)=>Jl(t,r,o,{callee:t.parseAsync}),t.safeParseAsync=async(r,o)=>Yl(t,r,o),t.spa=t.safeParseAsync,t.refine=(r,o)=>t.check(M_(r,o)),t.superRefine=r=>t.check(q_(r)),t.overwrite=r=>t.check(_t(r)),t.optional=()=>ee(t),t.nullable=()=>ep(t),t.nullish=()=>ee(ep(t)),t.nonoptional=r=>O_(t,r),t.array=()=>j(t),t.or=r=>J([t,r]),t.and=r=>bo(t,r),t.transform=r=>ws(t,ip(r)),t.default=r=>P_(t,r),t.prefault=r=>I_(t,r),t.catch=r=>A_(t,r),t.pipe=r=>ws(t,r),t.readonly=()=>Z_(t),t.describe=r=>{let o=t.clone();return cr.add(o,{description:r}),o},Object.defineProperty(t,"description",{get(){return cr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return cr.get(t);let o=t.clone();return cr.add(o,r[0]),o},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),tp=h("_ZodString",(t,e)=>{po.init(t,e),te.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...o)=>t.check(us(...o)),t.includes=(...o)=>t.check(ds(...o)),t.startsWith=(...o)=>t.check(fs(...o)),t.endsWith=(...o)=>t.check(ms(...o)),t.min=(...o)=>t.check(It(...o)),t.max=(...o)=>t.check(_o(...o)),t.length=(...o)=>t.check(go(...o)),t.nonempty=(...o)=>t.check(It(1,...o)),t.lowercase=o=>t.check(ls(o)),t.uppercase=o=>t.check(ps(o)),t.trim=()=>t.check(_s()),t.normalize=(...o)=>t.check(hs(...o)),t.toLowerCase=()=>t.check(gs()),t.toUpperCase=()=>t.check(ys())}),Yh=h("ZodString",(t,e)=>{po.init(t,e),tp.init(t,e),t.email=r=>t.check(ul(Xh,r)),t.url=r=>t.check(ml(Qh,r)),t.jwt=r=>t.check(Pl(m_,r)),t.emoji=r=>t.check(hl(e_,r)),t.guid=r=>t.check(cs(Xl,r)),t.uuid=r=>t.check(ll(So,r)),t.uuidv4=r=>t.check(pl(So,r)),t.uuidv6=r=>t.check(dl(So,r)),t.uuidv7=r=>t.check(fl(So,r)),t.nanoid=r=>t.check(_l(t_,r)),t.guid=r=>t.check(cs(Xl,r)),t.cuid=r=>t.check(gl(r_,r)),t.cuid2=r=>t.check(yl(o_,r)),t.ulid=r=>t.check(vl(n_,r)),t.base64=r=>t.check(zl(p_,r)),t.base64url=r=>t.check(El(d_,r)),t.xid=r=>t.check($l(s_,r)),t.ksuid=r=>t.check(Sl(i_,r)),t.ipv4=r=>t.check(bl(a_,r)),t.ipv6=r=>t.check(Tl(c_,r)),t.cidrv4=r=>t.check(wl(u_,r)),t.cidrv6=r=>t.check(xl(l_,r)),t.e164=r=>t.check(kl(f_,r)),t.datetime=r=>t.check(vs(r)),t.date=r=>t.check($s(r)),t.time=r=>t.check(Ss(r)),t.duration=r=>t.check(bs(r))});function f(t){return cl(Yh,t)}var X=h("ZodStringFormat",(t,e)=>{B.init(t,e),tp.init(t,e)}),Xh=h("ZodEmail",(t,e)=>{gu.init(t,e),X.init(t,e)});var Xl=h("ZodGUID",(t,e)=>{hu.init(t,e),X.init(t,e)});var So=h("ZodUUID",(t,e)=>{_u.init(t,e),X.init(t,e)});var Qh=h("ZodURL",(t,e)=>{yu.init(t,e),X.init(t,e)});var e_=h("ZodEmoji",(t,e)=>{vu.init(t,e),X.init(t,e)});var t_=h("ZodNanoID",(t,e)=>{$u.init(t,e),X.init(t,e)});var r_=h("ZodCUID",(t,e)=>{Su.init(t,e),X.init(t,e)});var o_=h("ZodCUID2",(t,e)=>{bu.init(t,e),X.init(t,e)});var n_=h("ZodULID",(t,e)=>{Tu.init(t,e),X.init(t,e)});var s_=h("ZodXID",(t,e)=>{wu.init(t,e),X.init(t,e)});var i_=h("ZodKSUID",(t,e)=>{xu.init(t,e),X.init(t,e)});var a_=h("ZodIPv4",(t,e)=>{Ru.init(t,e),X.init(t,e)});var c_=h("ZodIPv6",(t,e)=>{Iu.init(t,e),X.init(t,e)});var u_=h("ZodCIDRv4",(t,e)=>{Ou.init(t,e),X.init(t,e)});var l_=h("ZodCIDRv6",(t,e)=>{Nu.init(t,e),X.init(t,e)});var p_=h("ZodBase64",(t,e)=>{Cu.init(t,e),X.init(t,e)});var d_=h("ZodBase64URL",(t,e)=>{ju.init(t,e),X.init(t,e)});var f_=h("ZodE164",(t,e)=>{Zu.init(t,e),X.init(t,e)});var m_=h("ZodJWT",(t,e)=>{Du.init(t,e),X.init(t,e)});var rp=h("ZodNumber",(t,e)=>{ss.init(t,e),te.init(t,e),t.gt=(o,n)=>t.check(mo(o,n)),t.gte=(o,n)=>t.check(lr(o,n)),t.min=(o,n)=>t.check(lr(o,n)),t.lt=(o,n)=>t.check(fo(o,n)),t.lte=(o,n)=>t.check(ur(o,n)),t.max=(o,n)=>t.check(ur(o,n)),t.int=o=>t.check(Ql(o)),t.safe=o=>t.check(Ql(o)),t.positive=o=>t.check(mo(0,o)),t.nonnegative=o=>t.check(lr(0,o)),t.negative=o=>t.check(fo(0,o)),t.nonpositive=o=>t.check(ur(0,o)),t.multipleOf=(o,n)=>t.check(ho(o,n)),t.step=(o,n)=>t.check(ho(o,n)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function U(t){return Al(rp,t)}var h_=h("ZodNumberFormat",(t,e)=>{Mu.init(t,e),rp.init(t,e)});function Ql(t){return Cl(h_,t)}var __=h("ZodBoolean",(t,e)=>{qu.init(t,e),te.init(t,e)});function ie(t){return jl(__,t)}var g_=h("ZodNull",(t,e)=>{Lu.init(t,e),te.init(t,e)});function op(t){return Zl(g_,t)}var y_=h("ZodUnknown",(t,e)=>{Uu.init(t,e),te.init(t,e)});function Q(){return Dl(y_)}var v_=h("ZodNever",(t,e)=>{Fu.init(t,e),te.init(t,e)});function $_(t){return Ml(v_,t)}var S_=h("ZodArray",(t,e)=>{Vu.init(t,e),te.init(t,e),t.element=e.element,t.min=(r,o)=>t.check(It(r,o)),t.nonempty=r=>t.check(It(1,r)),t.max=(r,o)=>t.check(_o(r,o)),t.length=(r,o)=>t.check(go(r,o)),t.unwrap=()=>t.element});function j(t,e){return ql(S_,t,e)}var np=h("ZodObject",(t,e)=>{Hu.init(t,e),te.init(t,e),L.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Se(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Q()}),t.loose=()=>t.clone({...t._zod.def,catchall:Q()}),t.strict=()=>t.clone({...t._zod.def,catchall:$_()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>L.extend(t,r),t.merge=r=>L.merge(t,r),t.pick=r=>L.pick(t,r),t.omit=r=>L.omit(t,r),t.partial=(...r)=>L.partial(ap,t,r[0]),t.required=(...r)=>L.required(cp,t,r[0])});function T(t,e){let r={type:"object",get shape(){return L.assignProp(this,"shape",{...t}),this.shape},...L.normalizeParams(e)};return new np(r)}function ye(t,e){return new np({type:"object",get shape(){return L.assignProp(this,"shape",{...t}),this.shape},catchall:Q(),...L.normalizeParams(e)})}var sp=h("ZodUnion",(t,e)=>{is.init(t,e),te.init(t,e),t.options=e.options});function J(t,e){return new sp({type:"union",options:t,...L.normalizeParams(e)})}var b_=h("ZodDiscriminatedUnion",(t,e)=>{sp.init(t,e),Ku.init(t,e)});function xs(t,e,r){return new b_({type:"union",options:e,discriminator:t,...L.normalizeParams(r)})}var T_=h("ZodIntersection",(t,e)=>{Gu.init(t,e),te.init(t,e)});function bo(t,e){return new T_({type:"intersection",left:t,right:e})}var w_=h("ZodRecord",(t,e)=>{Bu.init(t,e),te.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function G(t,e,r){return new w_({type:"record",keyType:t,valueType:e,...L.normalizeParams(r)})}var Ts=h("ZodEnum",(t,e)=>{Ju.init(t,e),te.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ts({...e,checks:[],...L.normalizeParams(n),entries:s})},t.exclude=(o,n)=>{let s={...e.entries};for(let i of o)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ts({...e,checks:[],...L.normalizeParams(n),entries:s})}});function Se(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Ts({type:"enum",entries:r,...L.normalizeParams(e)})}var x_=h("ZodLiteral",(t,e)=>{Wu.init(t,e),te.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function w(t,e){return new x_({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var z_=h("ZodTransform",(t,e)=>{Yu.init(t,e),te.init(t,e),t._zod.parse=(r,o)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(L.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(L.issue(i))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function ip(t){return new z_({type:"transform",transform:t})}var ap=h("ZodOptional",(t,e)=>{Xu.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ee(t){return new ap({type:"optional",innerType:t})}var E_=h("ZodNullable",(t,e)=>{Qu.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ep(t){return new E_({type:"nullable",innerType:t})}var k_=h("ZodDefault",(t,e)=>{el.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function P_(t,e){return new k_({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var R_=h("ZodPrefault",(t,e)=>{tl.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function I_(t,e){return new R_({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var cp=h("ZodNonOptional",(t,e)=>{rl.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function O_(t,e){return new cp({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var N_=h("ZodCatch",(t,e)=>{ol.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function A_(t,e){return new N_({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var C_=h("ZodPipe",(t,e)=>{nl.init(t,e),te.init(t,e),t.in=e.in,t.out=e.out});function ws(t,e){return new C_({type:"pipe",in:t,out:e})}var j_=h("ZodReadonly",(t,e)=>{sl.init(t,e),te.init(t,e)});function Z_(t){return new j_({type:"readonly",innerType:t})}var up=h("ZodCustom",(t,e)=>{il.init(t,e),te.init(t,e)});function D_(t){let e=new fe({check:"custom"});return e._zod.check=t,e}function lp(t,e){return Ll(up,t??(()=>!0),e)}function M_(t,e={}){return Ul(up,t,e)}function q_(t){let e=D_(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(L.issue(o,r.value,e._zod.def));else{let n=o;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(L.issue(n))}},t(r.value,r)));return e}function zs(t,e){return ws(ip(t),e)}ke(al());var ks="2025-11-25";var pp=[ks,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],nt="io.modelcontextprotocol/related-task",wo="2.0",ne=lp(t=>t!==null&&(typeof t=="object"||typeof t=="function")),dp=J([f(),U().int()]),fp=f(),Ax=ye({ttl:U().optional(),pollInterval:U().optional()}),L_=T({ttl:U().optional()}),U_=T({taskId:f()}),Ps=ye({progressToken:dp.optional(),[nt]:U_.optional()}),ze=T({_meta:Ps.optional()}),mr=ze.extend({task:L_.optional()}),mp=t=>mr.safeParse(t).success,ae=T({method:f(),params:ze.loose().optional()}),Pe=T({_meta:Ps.optional()}),Re=T({method:f(),params:Pe.loose().optional()}),ce=ye({_meta:Ps.optional()}),xo=J([f(),U().int()]),hp=T({jsonrpc:w(wo),id:xo,...ae.shape}).strict(),Rs=t=>hp.safeParse(t).success,_p=T({jsonrpc:w(wo),...Re.shape}).strict(),gp=t=>_p.safeParse(t).success,Is=T({jsonrpc:w(wo),id:xo,result:ce}).strict(),hr=t=>Is.safeParse(t).success;var C;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(C||(C={}));var Os=T({jsonrpc:w(wo),id:xo.optional(),error:T({code:U().int(),message:f(),data:Q().optional()})}).strict();var yp=t=>Os.safeParse(t).success;var vp=J([hp,_p,Is,Os]),Cx=J([Is,Os]),zo=ce.strict(),F_=Pe.extend({requestId:xo.optional(),reason:f().optional()}),Nt=Re.extend({method:w("notifications/cancelled"),params:F_}),V_=T({src:f(),mimeType:f().optional(),sizes:j(f()).optional(),theme:Se(["light","dark"]).optional()}),_r=T({icons:j(V_).optional()}),Ot=T({name:f(),title:f().optional()}),$p=Ot.extend({...Ot.shape,..._r.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),H_=bo(T({applyDefaults:ie().optional()}),G(f(),Q())),K_=zs(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,bo(T({form:H_.optional(),url:ne.optional()}),G(f(),Q()).optional())),G_=ye({list:ne.optional(),cancel:ne.optional(),requests:ye({sampling:ye({createMessage:ne.optional()}).optional(),elicitation:ye({create:ne.optional()}).optional()}).optional()}),B_=ye({list:ne.optional(),cancel:ne.optional(),requests:ye({tools:ye({call:ne.optional()}).optional()}).optional()}),J_=T({experimental:G(f(),ne).optional(),sampling:T({context:ne.optional(),tools:ne.optional()}).optional(),elicitation:K_.optional(),roots:T({listChanged:ie().optional()}).optional(),tasks:G_.optional(),extensions:G(f(),ne).optional()}),W_=ze.extend({protocolVersion:f(),capabilities:J_,clientInfo:$p}),gr=ae.extend({method:w("initialize"),params:W_});var Y_=T({experimental:G(f(),ne).optional(),logging:ne.optional(),completions:ne.optional(),prompts:T({listChanged:ie().optional()}).optional(),resources:T({subscribe:ie().optional(),listChanged:ie().optional()}).optional(),tools:T({listChanged:ie().optional()}).optional(),tasks:B_.optional(),extensions:G(f(),ne).optional()}),X_=ce.extend({protocolVersion:f(),capabilities:Y_,serverInfo:$p,instructions:f().optional()}),Ns=Re.extend({method:w("notifications/initialized"),params:Pe.optional()});var Eo=ae.extend({method:w("ping"),params:ze.optional()}),Q_=T({progress:U(),total:ee(U()),message:ee(f())}),eg=T({...Pe.shape,...Q_.shape,progressToken:dp}),ko=Re.extend({method:w("notifications/progress"),params:eg}),tg=ze.extend({cursor:fp.optional()}),yr=ae.extend({params:tg.optional()}),vr=ce.extend({nextCursor:fp.optional()}),rg=Se(["working","input_required","completed","failed","cancelled"]),$r=T({taskId:f(),status:rg,ttl:J([U(),op()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ee(U()),statusMessage:ee(f())}),At=ce.extend({task:$r}),og=Pe.merge($r),Sr=Re.extend({method:w("notifications/tasks/status"),params:og}),Po=ae.extend({method:w("tasks/get"),params:ze.extend({taskId:f()})}),Ro=ce.merge($r),Io=ae.extend({method:w("tasks/result"),params:ze.extend({taskId:f()})}),jx=ce.loose(),Oo=yr.extend({method:w("tasks/list")}),No=vr.extend({tasks:j($r)}),Ao=ae.extend({method:w("tasks/cancel"),params:ze.extend({taskId:f()})}),Sp=ce.merge($r),bp=T({uri:f(),mimeType:ee(f()),_meta:G(f(),Q()).optional()}),Tp=bp.extend({text:f()}),As=f().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wp=bp.extend({blob:As}),br=Se(["user","assistant"]),Ct=T({audience:j(br).optional(),priority:U().min(0).max(1).optional(),lastModified:dr.datetime({offset:!0}).optional()}),xp=T({...Ot.shape,..._r.shape,uri:f(),description:ee(f()),mimeType:ee(f()),size:ee(U()),annotations:Ct.optional(),_meta:ee(ye({}))}),ng=T({...Ot.shape,..._r.shape,uriTemplate:f(),description:ee(f()),mimeType:ee(f()),annotations:Ct.optional(),_meta:ee(ye({}))}),Cs=yr.extend({method:w("resources/list")}),sg=vr.extend({resources:j(xp)}),js=yr.extend({method:w("resources/templates/list")}),ig=vr.extend({resourceTemplates:j(ng)}),Zs=ze.extend({uri:f()}),ag=Zs,Ds=ae.extend({method:w("resources/read"),params:ag}),cg=ce.extend({contents:j(J([Tp,wp]))}),ug=Re.extend({method:w("notifications/resources/list_changed"),params:Pe.optional()}),lg=Zs,Ms=ae.extend({method:w("resources/subscribe"),params:lg}),pg=Zs,qs=ae.extend({method:w("resources/unsubscribe"),params:pg}),dg=Pe.extend({uri:f()}),fg=Re.extend({method:w("notifications/resources/updated"),params:dg}),mg=T({name:f(),description:ee(f()),required:ee(ie())}),hg=T({...Ot.shape,..._r.shape,description:ee(f()),arguments:ee(j(mg)),_meta:ee(ye({}))}),Ls=yr.extend({method:w("prompts/list")}),_g=vr.extend({prompts:j(hg)}),gg=ze.extend({name:f(),arguments:G(f(),f()).optional()}),Us=ae.extend({method:w("prompts/get"),params:gg}),Fs=T({type:w("text"),text:f(),annotations:Ct.optional(),_meta:G(f(),Q()).optional()}),Vs=T({type:w("image"),data:As,mimeType:f(),annotations:Ct.optional(),_meta:G(f(),Q()).optional()}),Hs=T({type:w("audio"),data:As,mimeType:f(),annotations:Ct.optional(),_meta:G(f(),Q()).optional()}),yg=T({type:w("tool_use"),name:f(),id:f(),input:G(f(),Q()),_meta:G(f(),Q()).optional()}),vg=T({type:w("resource"),resource:J([Tp,wp]),annotations:Ct.optional(),_meta:G(f(),Q()).optional()}),$g=xp.extend({type:w("resource_link")}),Ks=J([Fs,Vs,Hs,$g,vg]),Sg=T({role:br,content:Ks}),bg=ce.extend({description:f().optional(),messages:j(Sg)}),Tg=Re.extend({method:w("notifications/prompts/list_changed"),params:Pe.optional()}),wg=T({title:f().optional(),readOnlyHint:ie().optional(),destructiveHint:ie().optional(),idempotentHint:ie().optional(),openWorldHint:ie().optional()}),xg=T({taskSupport:Se(["required","optional","forbidden"]).optional()}),zp=T({...Ot.shape,..._r.shape,description:f().optional(),inputSchema:T({type:w("object"),properties:G(f(),ne).optional(),required:j(f()).optional()}).catchall(Q()),outputSchema:T({type:w("object"),properties:G(f(),ne).optional(),required:j(f()).optional()}).catchall(Q()).optional(),annotations:wg.optional(),execution:xg.optional(),_meta:G(f(),Q()).optional()}),Gs=yr.extend({method:w("tools/list")}),zg=vr.extend({tools:j(zp)}),Co=ce.extend({content:j(Ks).default([]),structuredContent:G(f(),Q()).optional(),isError:ie().optional()}),Zx=Co.or(ce.extend({toolResult:Q()})),Eg=mr.extend({name:f(),arguments:G(f(),Q()).optional()}),Tr=ae.extend({method:w("tools/call"),params:Eg}),kg=Re.extend({method:w("notifications/tools/list_changed"),params:Pe.optional()}),Dx=T({autoRefresh:ie().default(!0),debounceMs:U().int().nonnegative().default(300)}),wr=Se(["debug","info","notice","warning","error","critical","alert","emergency"]),Pg=ze.extend({level:wr}),Bs=ae.extend({method:w("logging/setLevel"),params:Pg}),Rg=Pe.extend({level:wr,logger:f().optional(),data:Q()}),Ig=Re.extend({method:w("notifications/message"),params:Rg}),Og=T({name:f().optional()}),Ng=T({hints:j(Og).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),Ag=T({mode:Se(["auto","required","none"]).optional()}),Cg=T({type:w("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:j(Ks).default([]),structuredContent:T({}).loose().optional(),isError:ie().optional(),_meta:G(f(),Q()).optional()}),jg=xs("type",[Fs,Vs,Hs]),To=xs("type",[Fs,Vs,Hs,yg,Cg]),Zg=T({role:br,content:J([To,j(To)]),_meta:G(f(),Q()).optional()}),Dg=mr.extend({messages:j(Zg),modelPreferences:Ng.optional(),systemPrompt:f().optional(),includeContext:Se(["none","thisServer","allServers"]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:j(f()).optional(),metadata:ne.optional(),tools:j(zp).optional(),toolChoice:Ag.optional()}),Mg=ae.extend({method:w("sampling/createMessage"),params:Dg}),xr=ce.extend({model:f(),stopReason:ee(Se(["endTurn","stopSequence","maxTokens"]).or(f())),role:br,content:jg}),Js=ce.extend({model:f(),stopReason:ee(Se(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:br,content:J([To,j(To)])}),qg=T({type:w("boolean"),title:f().optional(),description:f().optional(),default:ie().optional()}),Lg=T({type:w("string"),title:f().optional(),description:f().optional(),minLength:U().optional(),maxLength:U().optional(),format:Se(["email","uri","date","date-time"]).optional(),default:f().optional()}),Ug=T({type:Se(["number","integer"]),title:f().optional(),description:f().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),Fg=T({type:w("string"),title:f().optional(),description:f().optional(),enum:j(f()),default:f().optional()}),Vg=T({type:w("string"),title:f().optional(),description:f().optional(),oneOf:j(T({const:f(),title:f()})),default:f().optional()}),Hg=T({type:w("string"),title:f().optional(),description:f().optional(),enum:j(f()),enumNames:j(f()).optional(),default:f().optional()}),Kg=J([Fg,Vg]),Gg=T({type:w("array"),title:f().optional(),description:f().optional(),minItems:U().optional(),maxItems:U().optional(),items:T({type:w("string"),enum:j(f())}),default:j(f()).optional()}),Bg=T({type:w("array"),title:f().optional(),description:f().optional(),minItems:U().optional(),maxItems:U().optional(),items:T({anyOf:j(T({const:f(),title:f()}))}),default:j(f()).optional()}),Jg=J([Gg,Bg]),Wg=J([Hg,Kg,Jg]),Yg=J([Wg,qg,Lg,Ug]),Xg=mr.extend({mode:w("form").optional(),message:f(),requestedSchema:T({type:w("object"),properties:G(f(),Yg),required:j(f()).optional()})}),Qg=mr.extend({mode:w("url"),message:f(),elicitationId:f(),url:f().url()}),ey=J([Xg,Qg]),ty=ae.extend({method:w("elicitation/create"),params:ey}),ry=Pe.extend({elicitationId:f()}),oy=Re.extend({method:w("notifications/elicitation/complete"),params:ry}),jt=ce.extend({action:Se(["accept","decline","cancel"]),content:zs(t=>t===null?void 0:t,G(f(),J([f(),U(),ie(),j(f())])).optional())}),ny=T({type:w("ref/resource"),uri:f()});var sy=T({type:w("ref/prompt"),name:f()}),iy=ze.extend({ref:J([sy,ny]),argument:T({name:f(),value:f()}),context:T({arguments:G(f(),f()).optional()}).optional()}),ay=ae.extend({method:w("completion/complete"),params:iy});var cy=ce.extend({completion:ye({values:j(f()).max(100),total:ee(U().int()),hasMore:ee(ie())})}),uy=T({uri:f().startsWith("file://"),name:f().optional(),_meta:G(f(),Q()).optional()}),ly=ae.extend({method:w("roots/list"),params:ze.optional()}),Ws=ce.extend({roots:j(uy)}),py=Re.extend({method:w("notifications/roots/list_changed"),params:Pe.optional()}),Mx=J([Eo,gr,ay,Bs,Us,Ls,Cs,js,Ds,Ms,qs,Tr,Gs,Po,Io,Oo,Ao]),qx=J([Nt,ko,Ns,py,Sr]),Lx=J([zo,xr,Js,jt,Ws,Ro,No,At]),Ux=J([Eo,Mg,ty,ly,Po,Io,Oo,Ao]),Fx=J([Nt,ko,Ig,fg,ug,kg,Tg,Sr,oy]),Vx=J([zo,X_,cy,bg,_g,sg,ig,cg,Co,zg,Ro,No,At]),R=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===C.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Es(n.elicitations,r)}return new t(e,r,o)}},Es=class extends R{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(C.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function st(t){return t==="completed"||t==="failed"||t==="cancelled"}var Tz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ys(t){let r=vo(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=$o(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Xs(t,e){let r=ot(t,e);if(!r.success)throw r.error;return r.data}var gy=6e4,jo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Nt,r=>{this._oncancel(r)}),this.setNotificationHandler(ko,r=>{this._onprogress(r)}),this.setRequestHandler(Eo,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Po,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new R(C.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Io,async(r,o)=>{let n=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,o.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,d=new R(p.error.code,p.error.message,p.error.data);u(d)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:o.requestId})}}let i=await this._taskStore.getTask(s,o.sessionId);if(!i)throw new R(C.InvalidParams,`Task not found: ${s}`);if(!st(i.status))return await this._waitForTaskUpdate(s,o.signal),await n();if(st(i.status)){let a=await this._taskStore.getTaskResult(s,o.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[nt]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(Oo,async(r,o)=>{try{let{tasks:n,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(n){throw new R(C.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Ao,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new R(C.InvalidParams,`Task not found: ${r.params.taskId}`);if(st(n.status))throw new R(C.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!s)throw new R(C.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(n){throw n instanceof R?n:new R(C.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,o,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),R.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=s=>{o?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),hr(s)||yp(s)?this._onresponse(s):Rs(s)?this._onrequest(s,i):gp(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=R.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,s=e.params?._meta?.[nt]?.taskId;if(o===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:C.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},n?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):n?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=mp(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,l={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,d)=>{if(i.signal.aborted)throw new R(C.ConnectionClosed,"Request was cancelled");let m={...d,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let _=m.relatedTask?.taskId??s;return _&&c&&await c.updateTaskStatus(_,"input_required"),await this.request(u,p,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},n?.sessionId):await n?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:C.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},n?.sessionId):await n?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),hr(e))o(e);else{let i=new R(e.error.code,e.error.message,e.error.data);o(i)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(hr(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),hr(e))n(e);else{let i=R.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(i){yield{type:"error",error:i instanceof R?i:new R(C.InternalError,String(i))}}return}let s;try{let i=await this.request(e,At,o);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new R(C.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},o);if(yield{type:"taskStatus",task:a},st(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)}:a.status==="failed"?yield{type:"error",error:new R(C.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new R(C.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),o?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof R?i:new R(C.InternalError,String(i))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=o??{};return new Promise((l,u)=>{let p=b=>{u(b)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){p(b);return}o?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};o?.onprogress&&(this._progressHandlers.set(d,o.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[nt]:c}});let _=b=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(b)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(z=>this._onerror(new Error(`Failed to send cancellation: ${z}`)));let $=b instanceof R?b:new R(C.RequestTimeout,String(b));u($)};this._responseHandlers.set(d,b=>{if(!o?.signal?.aborted){if(b instanceof Error)return u(b);try{let $=ot(r,b.result);$.success?l($.data):u($.error)}catch($){u($)}}}),o?.signal?.addEventListener("abort",()=>{_(o?.signal?.reason)});let g=o?.timeout??gy,y=()=>_(R.fromError(C.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(d,g,o?.maxTotalTimeout,y,o?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=$=>{let z=this._responseHandlers.get(d);z?z($):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,b),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(d),u($)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(d),u(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ro,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},No,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Sp,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[nt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[nt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[nt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let o=Ys(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,s)=>{let i=Xs(e,n);return Promise.resolve(r(i,s))})}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,r){let o=Ys(e);this._notificationHandlers.set(o,n=>{let s=Xs(e,n);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&Rs(n.message)){let s=n.message.id,i=this._requestResolvers.get(s);i?(i(new R(C.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let o=this._options?.defaultTaskPollInterval??1e3;try{let n=await this._taskStore?.getTask(e);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,s)=>{if(r.aborted){s(new R(C.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(i),s(new R(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let s=await o.getTask(n,r);if(!s)throw new R(C.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(n,s,i)=>{await o.storeTaskResult(n,s,i,r);let a=await o.getTask(n,r);if(a){let c=Sr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),st(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,s,i)=>{let a=await o.getTask(n,r);if(!a)throw new R(C.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(st(a.status))throw new R(C.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,s,i,r);let c=await o.getTask(n,r);if(c){let l=Sr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),st(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function Ep(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function kp(t,e){let r={...t};for(let o in e){let n=o,s=e[n];if(s===void 0)continue;let i=r[n];Ep(i)&&Ep(s)?r[n]={...i,...s}:r[n]=s}return r}var vm=ac(Da(),1),$m=ac(ym(),1);function bT(){let t=new vm.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$m.default)(t),t}var $n=class{constructor(e){this._ajv=e??bT()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Sn=class{constructor(e){this._server=e}requestStream(e,r,o){return this._server.requestStream(e,r,o)}createMessageStream(e,r){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(s.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==p.size||![...u].every(d=>p.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},xr,r)}elicitInputStream(e,r){let o=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},jt,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._server.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Sm(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function bm(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var bn=class extends jo{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(wr.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let s=this._loggingLevels.get(n);return s?this.LOG_LEVEL_SEVERITY.get(o)this._oninitialize(o)),this.setNotificationHandler(Ns,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Bs,async(o,n)=>{let s=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=o.params,a=wr.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Sn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=kp(this._capabilities,e)}setRequestHandler(e,r){let n=vo(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let s=$o(n);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=ot(Tr,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new R(C.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:p}=u.data,d=await Promise.resolve(r(c,l));if(p.task){let _=ot(At,d);if(!_.success){let g=_.error instanceof Error?_.error.message:String(_.error);throw new R(C.InvalidParams,`Invalid task creation result: ${g}`)}return _.data}let m=ot(Co,d);if(!m.success){let _=m.error instanceof Error?m.error.message:String(m.error);throw new R(C.InvalidParams,`Invalid tools/call result: ${_}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new 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 new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new 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 new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new 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 new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){bm(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Sm(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:pp.includes(r)?r:ks,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"},zo)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],s=n.some(l=>l.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]:[],c=a.some(l=>l.type==="tool_use");if(s){if(n.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(n.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new 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},Js,r):this.request({method:"sampling/createMessage",params:e},xr,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},jt,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:n},jt,r);if(s.action==="accept"&&s.content&&n.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(n.requestedSchema)(s.content);if(!a.valid)throw new R(C.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof R?i:new R(C.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ws,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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"})}};import wm from"node:process";var TT=10*1024*1024,Tn=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??TT}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` -`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),wT(r)}clear(){this._buffer=void 0}};function wT(t){return vp.parse(JSON.parse(t))}function Tm(t){return JSON.stringify(t)+` -`}var wn=class{constructor(e=wm.stdin,r=wm.stdout,o){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=n=>{this.onerror?.(n)},this._readBuffer=new Tn({maxBufferSize:o?.maxBufferSize})}async start(){if(this._started)throw new 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(r=>{let o=Tm(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var xn=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,o){if(e.length>r)throw new Error(`${o} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],o="",n=0,s=0;for(;n1e4)throw new Error("Template contains too many expressions (max 10000)");let a=e.slice(n+1,i),c=this.getOperator(a),l=a.includes("*"),u=this.getNames(a),p=u[0];for(let d of u)t.validateLength(d,1e6,"Variable name");r.push({name:p,operator:c,names:u,exploded:l}),n=i+1}else o+=e[n],n++;return o&&r.push(o),r}getOperator(e){return["+","#",".","/","?","&"].find(o=>e.startsWith(o))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(o=>o.replace("*","").trim()).filter(o=>o.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let i=e.names.map(c=>{let l=r[c];if(l===void 0)return"";let u=Array.isArray(l)?l.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(l.toString(),e.operator);return`${c}=${u}`}).filter(c=>c.length>0);return i.length===0?"":(e.operator==="?"?"?":"&")+i.join("&")}if(e.names.length>1){let i=e.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let o=r[e.name];if(o===void 0)return"";let s=(Array.isArray(o)?o:[o]).map(i=>this.encodeValue(i,e.operator));switch(e.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(e){let r="",o=!1;for(let n of this.parts){if(typeof n=="string"){r+=n;continue}let s=this.expandPart(n,e);s&&((n.operator==="?"||n.operator==="&")&&o?r+=s.replace("?","&"):r+=s,(n.operator==="?"||n.operator==="&")&&(o=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let s of e.names)t.validateLength(s,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s0?"identity-response-secret".repeat(Ya):void 0,FT=rc===void 0?process.env.TEST_IDENTITY_RESPONSE??JSON.stringify({login:Pn}):JSON.stringify({login:rc}),VT=process.env.TEST_IDENTITY_SCHEMA==="min-properties"?{type:"object",properties:{account:{type:"string"}},minProperties:1}:process.env.TEST_IDENTITY_SCHEMA==="all-of-required"?{type:"object",properties:{account:{type:"string"}},allOf:[{required:["account"]}]}:process.env.TEST_IDENTITY_SCHEMA==="additional-properties-false"?{type:"object",properties:{},additionalProperties:!1}:{type:"object",properties:{}},oc=process.env.TEST_INCLUDE_SAFE_READ_TOOL==="true"?"get_capabilities":void 0,rh=process.env.TEST_SAFE_READ_CALL_PATH,HT=process.env.TEST_SAFE_READ_RESPONSE??"safe-read",oh=lh(process.env.TEST_SAFE_READ_ANNOTATIONS,"TEST_SAFE_READ_ANNOTATIONS"),KT=process.env.TEST_SAFE_READ_SCHEMA==="required"?{type:"object",properties:{account:{type:"string"}},required:["account"]}:process.env.TEST_SAFE_READ_SCHEMA==="all-of-required"?{type:"object",properties:{},allOf:[{required:["account"]}]}:{type:"object",properties:{}},Xa=0,nh=process.env.TEST_ISOLATION_REPORT_PATH;if(nh){let t=process.env.OAUTH_CREDENTIAL_PATH;if(!t)throw new Error("test isolation fixture requires OAUTH_CREDENTIAL_PATH");let e=xT(t,"utf8");de(nh,JSON.stringify({home:process.env.HOME,xdgConfigHome:process.env.XDG_CONFIG_HOME,xdgCacheHome:process.env.XDG_CACHE_HOME,xdgDataHome:process.env.XDG_DATA_HOME,xdgStateHome:process.env.XDG_STATE_HOME,xdgRuntimeDir:process.env.XDG_RUNTIME_DIR,credentialPath:t,credential:e})),process.env.TEST_ISOLATION_EMIT_CREDENTIAL==="true"&&process.stderr.write(`test isolated credential: ${e} -`);let r=process.env.TEST_ISOLATION_EMIT_CREDENTIAL_FIELD;if(r){let o=JSON.parse(e)[r];if(typeof o!="string")throw new Error("test isolation fixture requires a string credential field");process.stderr.write(`test isolated credential field: ${o} -`)}}Jm&&Le(Jm,`1 -`);if(process.env.TEST_HANG_ON_START==="true"||En&&Je(En))if(th&&de(th,"ready"),En)for(;Je(En);)await se(5);else for(;;)await se(1e3);(Wa||Ja>0)&&process.stdin.once("end",()=>{Wa&&de(Wa,"ended"),Ja>0&&se(Ja).then(()=>process.exit(0))});process.env.TEST_IGNORE_SIGTERM==="true"&&process.on("SIGTERM",()=>{});ro&&(zn>0&&zn{Wm&&de(Wm,"initialized"),Bm&&Je(Bm)&&se(0).then(()=>process.exit(1))};function lh(t,e){if(t!==void 0)try{return JSON.parse(t)}catch{throw new Error(`${e} must contain valid JSON`)}}(eh||Ba)&&re.setRequestHandler(gr,async t=>{if(Ba&&de(Ba,JSON.stringify(t.params.clientInfo)),eh)throw new Error(`test initialize failure: ${process.env.API_TOKEN}`);return{protocolVersion:t.params.protocolVersion,capabilities:{tools:{},resources:Cn?{subscribe:!0}:{},prompts:{}},serverInfo:{name:"fake-upstream",version:"1.0.0"}}});re.setRequestHandler(Gs,async t=>{Xa+=1;let e=ZT&&Xa>1;if(zm>0&&await se(zm),process.env.TEST_LIST_TOOLS_STARTED_PATH&&de(process.env.TEST_LIST_TOOLS_STARTED_PATH,"started"),process.env.TEST_LIST_TOOLS_COUNT_PATH&&Le(process.env.TEST_LIST_TOOLS_COUNT_PATH,`1 -`),xm>0&&await se(xm),zT&&t.params._meta?.progressToken!==void 0&&await re.notification({method:"notifications/progress",params:{progressToken:t.params._meta.progressToken,progress:1,total:2}}),process.env.TEST_FAIL_LIST_TOOLS==="true")throw new Error(`test tool list failure: ${process.env.TEST_ERROR_MESSAGE??process.env.API_TOKEN}`);(CT||jT&&Xa===1)&&await re.sendToolListChanged(),Em>0&&await se(Em);let r=Um&&t.params?.cursor==="next";return{tools:[...uh?[{name:"exec",description:"Execute a PostHog command.",inputSchema:{type:"object",properties:{command:{type:"string"},context:{type:"string"}},required:["command","context"],additionalProperties:!1}}]:r?[{name:"whoami_second",description:"Return the second injected account.",inputSchema:sh},{name:"echo_second",description:"Echo a second message.",inputSchema:{type:"object",properties:{message:{type:"string"}},required:["message"]}},{name:"create_second_item",description:"Create a second item.",inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]}}]:[{name:e?"whoami_reloaded":"whoami",description:process.env.TEST_INCLUDE_DISCOVERY_TOKEN==="true"?`Return the injected account ${process.env.API_TOKEN}`:"Return the injected account.",inputSchema:sh},{name:e?"echo_reloaded":"echo",description:"Echo a message.",inputSchema:{type:"object",properties:{message:{type:"string"}},required:["message"]}},{name:e?"create_reloaded_item":"create_item",description:"Create an item.",inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},...ih===void 0?{}:{annotations:ih}}],...UT&&!r?[{name:"identity",description:"Return the configured account identity.",inputSchema:VT}]:[],...oc&&!r?[{name:oc,description:"Run the provider-declared empty-object readiness probe.",inputSchema:KT,...oh===void 0?{}:{annotations:oh}}]:[],...process.env.TEST_INCLUDE_MANAGEMENT_TOOL==="true"?[{name:"miftah_health",description:"Collides with a reserved Miftah management tool.",inputSchema:{type:"object",properties:{}}}]:[],...process.env.TEST_INCLUDE_MIFTAH_PREFIX_TOOL==="true"?[{name:"miftah_custom",description:"An upstream tool with a Miftah-looking name.",inputSchema:{type:"object",properties:{}}}]:[]],...Um&&!r?{nextCursor:"next"}:{}}});re.setRequestHandler(Tr,async t=>{if(Xm&&de(Xm,"started"),An&&Je(An))return se(0).then(()=>process.exit(1)),new Promise(()=>{});if(process.env.TEST_CALL_TOOL_COUNT_PATH&&Le(process.env.TEST_CALL_TOOL_COUNT_PATH,`1 -`),t.params.name==="create_item"&&Ym&&Le(Ym,`1 -`),process.env.TEST_FAIL_CALL_TOOL==="true")throw new Error(`test tool call failure: ${process.env.API_TOKEN}`);return process.env.TEST_RETURN_CALL_TOOL_ERROR==="true"?{content:[{type:"text",text:"test tool returned an error result"}],isError:!0}:(RT&&t.params._meta?.progressToken!==void 0&&await re.notification({method:"notifications/progress",params:{progressToken:t.params._meta.progressToken,progress:1,total:2,...Im===void 0?{}:{message:Im}}}),DT&&await Promise.all([re.sendToolListChanged(),re.sendResourceListChanged(),re.sendPromptListChanged()]),Rm>0&&await se(Rm),uh&&t.params.name==="exec"?{content:[{type:"text",text:`exec:${String(t.params.arguments?.command??"")}`}]}:t.params.name==="whoami"?{content:[{type:"text",text:rc??Pn}]}:t.params.name==="identity"?{content:[{type:"text",text:FT}]}:t.params.name===oc?(rh&&de(rh,JSON.stringify({name:t.params.name,arguments:t.params.arguments??{}})),{content:[{type:"text",text:HT}]}):t.params.name==="echo"?{content:[{type:"text",text:String(t.params.arguments?.message??"")}]}:{content:[{type:"text",text:`created:${String(t.params.arguments?.name??"")}`}]})});re.setNotificationHandler(Nt,t=>{Qm&&Le(Qm,`${t.params.requestId} -`)});re.setRequestHandler(Cs,async t=>{if(process.env.TEST_LIST_RESOURCES_COUNT_PATH&&Le(process.env.TEST_LIST_RESOURCES_COUNT_PATH,`1 -`),process.env.TEST_LIST_RESOURCES_STARTED_PATH&&de(process.env.TEST_LIST_RESOURCES_STARTED_PATH,"started"),km>0&&await se(km),ET&&t.params._meta?.progressToken!==void 0&&await re.notification({method:"notifications/progress",params:{progressToken:t.params._meta.progressToken,progress:1,total:2}}),process.env.TEST_FAIL_LIST_RESOURCES==="true"||Hm&&Je(Hm))throw new Error(`test resource discovery failure: ${process.env.API_TOKEN}`);let e=On&&t.params?.cursor==="next";return{resources:[{uri:e?qT:ah,name:process.env.TEST_INCLUDE_DISCOVERY_TOKEN==="true"?`Current account ${process.env.API_TOKEN}`:e?MT:IT,mimeType:"text/plain",...Vm?{icons:[{src:Vm}]}:{}}],...On&&!e?{nextCursor:"next"}:{}}});NT||re.setRequestHandler(js,async t=>(kT&&t.params._meta?.progressToken!==void 0&&await re.notification({method:"notifications/progress",params:{progressToken:t.params._meta.progressToken,progress:1,total:2}}),{resourceTemplates:In===void 0?[]:[{uriTemplate:In,name:OT,mimeType:"text/plain"}]}));re.setRequestHandler(Ds,async t=>{if(process.env.TEST_READ_RESOURCE_COUNT_PATH&&Le(process.env.TEST_READ_RESOURCE_COUNT_PATH,`1 -`),process.env.TEST_READ_RESOURCE_STARTED_PATH&&de(process.env.TEST_READ_RESOURCE_STARTED_PATH,"started"),Om>0&&await se(Om),process.env.TEST_FAIL_READ_RESOURCE==="true")throw new Error(`test resource read failure: ${process.env.TEST_ERROR_URI??process.env.API_TOKEN}`);return{contents:[{uri:In!==void 0&&new xn(In).match(t.params.uri)!==null?t.params.uri:ah,text:Rn,mimeType:"text/plain"},...Fm?[{uri:Fm,text:Rn,mimeType:"text/plain"}]:[]]}});re.setRequestHandler(Ms,async()=>{if(!Cn)throw new Error("test upstream does not support resource subscriptions");if(jm>0&&await se(jm),Lm&&de(Lm,"started"),Mm&&Le(Mm,`1 -`),Zm>0&&await se(Zm),AT)throw new Error("test subscribe failure");let t=kn?++tc:void 0;if(kn&&(ec=!0),Am){let e=async()=>{kn&&(!ec||tc!==t)||await re.sendResourceUpdated({uri:Am})};Cm>0?se(Cm).then(e):await e()}return{}});re.setRequestHandler(qs,async()=>{if(!Cn)throw new Error("test upstream does not support resource subscriptions");return qm&&Le(qm,`1 -`),Dm>0&&await se(Dm),kn&&(ec=!1,tc+=1),{}});re.setRequestHandler(Ls,async t=>{if(process.env.TEST_LIST_PROMPTS_COUNT_PATH&&Le(process.env.TEST_LIST_PROMPTS_COUNT_PATH,`1 -`),process.env.TEST_LIST_PROMPTS_STARTED_PATH&&de(process.env.TEST_LIST_PROMPTS_STARTED_PATH,"started"),Pm>0&&await se(Pm),PT&&t.params._meta?.progressToken!==void 0&&await re.notification({method:"notifications/progress",params:{progressToken:t.params._meta.progressToken,progress:1,total:2}}),process.env.TEST_FAIL_LIST_PROMPTS==="true"||Km&&Je(Km))throw new Error(`test prompt discovery failure: ${process.env.API_TOKEN}`);let e=On&&t.params?.cursor==="next";return{prompts:[{name:e?LT:ch,description:process.env.TEST_INCLUDE_DISCOVERY_TOKEN==="true"?`Account prompt ${process.env.API_TOKEN}`:e?"Second account prompt":"Account prompt",...Nn?{icons:[{src:Nn}]}:{}}],...On&&!e?{nextCursor:"next"}:{}}});re.setRequestHandler(Us,async()=>{if(process.env.TEST_GET_PROMPT_COUNT_PATH&&Le(process.env.TEST_GET_PROMPT_COUNT_PATH,`1 -`),process.env.TEST_GET_PROMPT_STARTED_PATH&&de(process.env.TEST_GET_PROMPT_STARTED_PATH,"started"),Nm>0&&await se(Nm),process.env.TEST_FAIL_GET_PROMPT==="true")throw new Error(`test prompt get failure: ${process.env.TEST_ERROR_URI??process.env.API_TOKEN}`);return{description:ch,messages:[{role:"user",content:{type:"text",text:Rn}},...Ka?[{role:"assistant",content:{type:"resource_link",uri:Ka,name:"Account resource",...Nn?{icons:[{src:Nn}]}:{}}},{role:"assistant",content:{type:"resource",resource:{uri:Ka,text:Rn,mimeType:"text/plain"}}}]:[]]}});await re.connect(new wn); + + `)}R.write("payload.value = newResult;"),R.write("return payload;");let _=R.compile();return(p,S)=>_(z,p,S)},i,a=nr,c=!Ho.jitless,l=c&&Is.value,m=t.catchall,h;e._zod.parse=(z,R)=>{h??(h=n.value);let v=z.value;return a(v)?c&&l&&R?.async===!1&&R.jitless!==!0?(i||(i=o(t.shape)),z=i(z,R),m?zm([],v,z,R,h,e):z):r(z,R):(z.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),z)}});function qd(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!Ct(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>ct(a,n,We())))}),t)}var Vs=q("$ZodUnion",(e,t)=>{ye.init(e,t),Se(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Se(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Se(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Se(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>On(i.source)).join("|")})$`)}});let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let a=!1,c=[];for(let s of t.options){let l=s._zod.run({value:o.value,issues:[]},i);if(l instanceof Promise)c.push(l),a=!0;else{if(l.issues.length===0)return l;c.push(l)}}return a?Promise.all(c).then(s=>qd(s,o,e,i)):qd(c,o,e,i)}});var wm=q("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Vs.init(e,t);let r=e._zod.parse;Se(e._zod,"propValues",()=>{let o={};for(let i of t.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[c,s]of Object.entries(a)){o[c]||(o[c]=new Set);for(let l of s)o[c].add(l)}}return o});let n=Ir(()=>{let o=t.options,i=new Map;for(let a of o){let c=a._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let s of c){if(i.has(s))throw new Error(`Duplicate discriminator value "${String(s)}"`);i.set(s,a)}}return i});e._zod.parse=(o,i)=>{let a=o.value;if(!nr(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;let c=n.value.get(a?.[t.discriminator]);return c?c._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),o)}}),Tm=q("$ZodIntersection",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([s,l])=>Md(r,s,l)):Md(r,i,a)}});function Us(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(xt(e)&&xt(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let a=Us(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n{ye.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!xt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],a=t.keyType._zod.values;if(a){r.value={};let c=new Set;for(let l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){c.add(typeof l=="number"?l.toString():l);let m=t.valueType._zod.run({value:o[l],issues:[]},n);m instanceof Promise?i.push(m.then(h=>{h.issues.length&&r.issues.push(...yt(l,h.issues)),r.value[l]=h.value})):(m.issues.length&&r.issues.push(...yt(l,m.issues)),r.value[l]=m.value)}let s;for(let l in o)c.has(l)||(s=s??[],s.push(l));s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:s})}else{r.value={};for(let c of Reflect.ownKeys(o)){if(c==="__proto__")continue;let s=t.keyType._zod.run({value:c,issues:[]},n);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){t.mode==="loose"?r.value[c]=o[c]:r.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(m=>ct(m,n,We())),input:c,path:[c],inst:e});continue}let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(m=>{m.issues.length&&r.issues.push(...yt(c,m.issues)),r.value[s.value]=m.value})):(l.issues.length&&r.issues.push(...yt(c,l.issues)),r.value[s.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Im=q("$ZodEnum",(e,t)=>{ye.init(e,t);let r=Pn(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>Ps.has(typeof o)).map(o=>typeof o=="string"?ht(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let a=o.value;return n.has(a)||o.issues.push({code:"invalid_value",values:r,input:a,inst:e}),o}}),Pm=q("$ZodLiteral",(e,t)=>{if(ye.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?ht(n):n?ht(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}});var km=q("$ZodTransform",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Tr(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new ft;return r.value=o,r}});function Ud(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Om=q("$ZodOptional",(e,t)=>{ye.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Se(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${On(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Ud(i,r.value)):Ud(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),jm=q("$ZodNullable",(e,t)=>{ye.init(e,t),Se(e._zod,"optin",()=>t.innerType._zod.optin),Se(e._zod,"optout",()=>t.innerType._zod.optout),Se(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${On(r.source)}|null)$`):void 0}),Se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Nm=q("$ZodDefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",Se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Ld(i,t)):Ld(o,t)}});function Ld(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var xm=q("$ZodPrefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",Se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Cm=q("$ZodNonOptional",(e,t)=>{ye.init(e,t),Se(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Dd(i,e)):Dd(o,e)}});function Dd(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Am=q("$ZodCatch",(e,t)=>{ye.init(e,t),Se(e._zod,"optin",()=>t.innerType._zod.optin),Se(e._zod,"optout",()=>t.innerType._zod.optout),Se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(a=>ct(a,n,We()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>ct(i,n,We()))},input:r.value}),r.issues=[]),r)}});var qm=q("$ZodPipe",(e,t)=>{ye.init(e,t),Se(e._zod,"values",()=>t.in._zod.values),Se(e._zod,"optin",()=>t.in._zod.optin),Se(e._zod,"optout",()=>t.out._zod.optout),Se(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);return i instanceof Promise?i.then(a=>Xo(a,t.in,n)):Xo(i,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>Xo(i,t.out,n)):Xo(o,t.out,n)}});function Xo(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var Mm=q("$ZodReadonly",(e,t)=>{ye.init(e,t),Se(e._zod,"propValues",()=>t.innerType._zod.propValues),Se(e._zod,"values",()=>t.innerType._zod.values),Se(e._zod,"optin",()=>t.innerType?._zod?.optin),Se(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Vd):Vd(o)}});function Vd(e){return e.value=Object.freeze(e.value),e}var Um=q("$ZodLazy",(e,t)=>{ye.init(e,t),Se(e._zod,"innerType",()=>t.getter()),Se(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Se(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Se(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Se(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Lm=q("$ZodCustom",(e,t)=>{Ve.init(e,t),ye.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>Zd(i,r,n,e));Zd(o,r,n,e)}});function Zd(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Pr(o))}}var hv=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},gv=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${hv(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ue(n.values[0])}`:`Invalid option: expected one of ${ce(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${ce(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Zs(){return{localeError:gv()}}var Vm;var Fs=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Zm(){return new Fs}(Vm=globalThis).__zod_globalRegistry??(Vm.__zod_globalRegistry=Zm());var bt=globalThis.__zod_globalRegistry;function Fm(e,t){return new e({type:"string",...re(t)})}function Hm(e,t){return new e({type:"string",coerce:!0,...re(t)})}function Hs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...re(t)})}function Js(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...re(t)})}function Jm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...re(t)})}function Bm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(t)})}function Km(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(t)})}function Gm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(t)})}function Bs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function Wm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...re(t)})}function Ym(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(t)})}function Xm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...re(t)})}function Qm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(t)})}function ep(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...re(t)})}function tp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...re(t)})}function rp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(t)})}function np(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(t)})}function op(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(t)})}function ip(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(t)})}function ap(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(t)})}function sp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...re(t)})}function cp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...re(t)})}function up(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...re(t)})}function lp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...re(t)})}function dp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(t)})}function mp(e,t){return new e({type:"string",format:"date",check:"string_format",...re(t)})}function pp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...re(t)})}function fp(e,t){return new e({type:"string",format:"duration",check:"string_format",...re(t)})}function hp(e,t){return new e({type:"number",checks:[],...re(t)})}function gp(e,t){return new e({type:"number",coerce:!0,checks:[],...re(t)})}function vp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function _p(e,t){return new e({type:"boolean",...re(t)})}function Sp(e,t){return new e({type:"boolean",coerce:!0,...re(t)})}function yp(e,t){return new e({type:"bigint",coerce:!0,...re(t)})}function bp(e,t){return new e({type:"null",...re(t)})}function $p(e){return new e({type:"any"})}function zp(e){return new e({type:"unknown"})}function Rp(e,t){return new e({type:"never",...re(t)})}function wp(e,t){return new e({type:"date",coerce:!0,...re(t)})}function kr(e,t){return new qs({check:"less_than",...re(t),value:e,inclusive:!1})}function $t(e,t){return new qs({check:"less_than",...re(t),value:e,inclusive:!0})}function Or(e,t){return new Ms({check:"greater_than",...re(t),value:e,inclusive:!1})}function ut(e,t){return new Ms({check:"greater_than",...re(t),value:e,inclusive:!0})}function Mn(e,t){return new $d({check:"multiple_of",...re(t),value:e})}function Un(e,t){return new Rd({check:"max_length",...re(t),maximum:e})}function or(e,t){return new wd({check:"min_length",...re(t),minimum:e})}function ei(e,t){return new Td({check:"length_equals",...re(t),length:e})}function Ks(e,t){return new Ed({check:"string_format",format:"regex",...re(t),pattern:e})}function Gs(e){return new Id({check:"string_format",format:"lowercase",...re(e)})}function Ws(e){return new Pd({check:"string_format",format:"uppercase",...re(e)})}function Ys(e,t){return new kd({check:"string_format",format:"includes",...re(t),includes:e})}function Xs(e,t){return new Od({check:"string_format",format:"starts_with",...re(t),prefix:e})}function Qs(e,t){return new jd({check:"string_format",format:"ends_with",...re(t),suffix:e})}function At(e){return new Nd({check:"overwrite",tx:e})}function ec(e){return At(t=>t.normalize(e))}function tc(){return At(e=>e.trim())}function rc(){return At(e=>e.toLowerCase())}function nc(){return At(e=>e.toUpperCase())}function oc(){return At(e=>Es(e))}function Tp(e,t,r){return new e({type:"array",element:t,...re(r)})}function Ep(e,t,r){return new e({type:"custom",check:"custom",fn:t,...re(r)})}function Ip(e){let t=bv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Pr(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Pr(o))}},e(r.value,r)));return t}function bv(e,t){let r=new Ve({check:"custom",...re(t)});return r._zod.check=e,r}function jr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??bt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function be(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let m={...r,schemaPath:[...r.schemaPath,e],path:r.path},h=e._zod.parent;if(h)a.ref=h,be(h,t,m),t.seen.get(h).isParent=!0;else if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,m);else{let z=a.schema,R=t.processors[o.type];if(!R)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);R(e,t,z,m)}}let s=t.metadataRegistry.get(e);return s&&Object.assign(a.schema,s),t.io==="input"&&Ye(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Nr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(i[0])?.id,h=e.external.uri??(R=>R);if(m)return{ref:h(m)};let z=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=z,{defId:z,ref:`${h("__shared")}#/${a}/${z}`}}if(i[1]===r)return{ref:"#"};let s=`#/${a}/`,l=i[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:s+l}},o=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:s}=n(i);a.def={...a.schema},s&&(a.defId=s);let l=a.schema;for(let m in l)delete l[m];l.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){o(i);continue}if(e.external){let s=e.external.registry.get(i[0])?.id;if(t!==i[0]&&s){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}if(a.count>1&&e.reused==="ref"){o(i);continue}}}function xr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=e.seen.get(a),s=c.def??c.schema,l={...s};if(c.ref===null)return;let m=c.ref;if(c.ref=null,m){n(m);let h=e.seen.get(m).schema;h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(s.allOf=s.allOf??[],s.allOf.push(h)):(Object.assign(s,h),Object.assign(s,l))}c.isParent||e.override({zodSchema:a,jsonSchema:s,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ln(t,"input"),output:Ln(t,"output")}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ye(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ye(n.element,r);if(n.type==="set")return Ye(n.valueType,r);if(n.type==="lazy")return Ye(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Ye(n.innerType,r);if(n.type==="intersection")return Ye(n.left,r)||Ye(n.right,r);if(n.type==="record"||n.type==="map")return Ye(n.keyType,r)||Ye(n.valueType,r);if(n.type==="pipe")return Ye(n.in,r)||Ye(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ye(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ye(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ye(o,r))return!0;return!!(n.rest&&Ye(n.rest,r))}return!1}var Pp=(e,t={})=>r=>{let n=jr({...r,processors:t});return be(e,n),Nr(n,e),xr(n,e)},Ln=(e,t)=>r=>{let{libraryOptions:n,target:o}=r??{},i=jr({...n??{},target:o,io:t,processors:{}});return be(e,i),Nr(i,e),xr(i,e)};var $v={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ac=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:a,format:c,patterns:s,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof a=="number"&&(o.maxLength=a),c&&(o.format=$v[c]??c,o.format===""&&delete o.format),l&&(o.contentEncoding=l),s&&s.size>0){let m=[...s];m.length===1?o.pattern=m[0].source:m.length>1&&(o.allOf=[...m.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},sc=(e,t,r,n)=>{let o=r,{minimum:i,maximum:a,format:c,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:m}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number",typeof m=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=m,o.exclusiveMinimum=!0):o.exclusiveMinimum=m),typeof i=="number"&&(o.minimum=i,typeof m=="number"&&t.target!=="draft-04"&&(m>=i?delete o.minimum:delete o.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=l,o.exclusiveMaximum=!0):o.exclusiveMaximum=l),typeof a=="number"&&(o.maximum=a,typeof l=="number"&&t.target!=="draft-04"&&(l<=a?delete o.maximum:delete o.exclusiveMaximum)),typeof s=="number"&&(o.multipleOf=s)},cc=(e,t,r,n)=>{r.type="boolean"},uc=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},kp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},lc=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Op=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},jp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},dc=(e,t,r,n)=>{r.not={}},mc=(e,t,r,n)=>{},pc=(e,t,r,n)=>{},fc=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},hc=(e,t,r,n)=>{let o=e._zod.def,i=Pn(o.entries);i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},gc=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let a of o.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Np=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},xp=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Cp=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:c,mime:s}=e._zod.bag;a!==void 0&&(i.minLength=a),c!==void 0&&(i.maxLength=c),s?s.length===1?(i.contentMediaType=s[0],Object.assign(o,i)):o.anyOf=s.map(l=>({...i,contentMediaType:l})):Object.assign(o,i)},Ap=(e,t,r,n)=>{r.type="boolean"},vc=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},qp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},_c=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Mp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Up=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Sc=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:a,maximum:c}=e._zod.bag;typeof a=="number"&&(o.minItems=a),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=be(i.element,t,{...n,path:[...n.path,"items"]})},yc=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let a=i.shape;for(let l in a)o.properties[l]=be(a[l],t,{...n,path:[...n.path,"properties",l]});let c=new Set(Object.keys(a)),s=new Set([...c].filter(l=>{let m=i.shape[l]._zod;return t.io==="input"?m.optin===void 0:m.optout===void 0}));s.size>0&&(o.required=Array.from(s)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=be(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},bc=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,a=o.options.map((c,s)=>be(c,t,{...n,path:[...n.path,i?"oneOf":"anyOf",s]}));i?r.oneOf=a:r.anyOf=a},$c=(e,t,r,n)=>{let o=e._zod.def,i=be(o.left,t,{...n,path:[...n.path,"allOf",0]}),a=be(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,s=[...c(i)?i.allOf:[i],...c(a)?a.allOf:[a]];r.allOf=s},Lp=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",c=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",s=i.items.map((z,R)=>be(z,t,{...n,path:[...n.path,a,R]})),l=i.rest?be(i.rest,t,{...n,path:[...n.path,c,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=s,l&&(o.items=l)):t.target==="openapi-3.0"?(o.items={anyOf:s},l&&o.items.anyOf.push(l),o.minItems=s.length,l||(o.maxItems=s.length)):(o.items=s,l&&(o.additionalItems=l));let{minimum:m,maximum:h}=e._zod.bag;typeof m=="number"&&(o.minItems=m),typeof h=="number"&&(o.maxItems=h)},zc=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=be(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=be(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})},Rc=(e,t,r,n)=>{let o=e._zod.def,i=be(o.innerType,t,n),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},wc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Tc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Ec=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Ic=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},Pc=(e,t,r,n)=>{let o=e._zod.def,i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;be(i,t,n);let a=t.seen.get(e);a.ref=i},kc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},Dp=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Oc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},jc=(e,t,r,n)=>{let o=e._zod.innerType;be(o,t,n);let i=t.seen.get(e);i.ref=o},ic={string:ac,number:sc,boolean:cc,bigint:uc,symbol:kp,null:lc,undefined:Op,void:jp,never:dc,any:mc,unknown:pc,date:fc,enum:hc,literal:gc,nan:Np,template_literal:xp,file:Cp,success:Ap,custom:vc,function:qp,transform:_c,map:Mp,set:Up,array:Sc,object:yc,union:bc,intersection:$c,tuple:Lp,record:zc,nullable:Rc,nonoptional:wc,default:Tc,prefault:Ec,catch:Ic,pipe:Pc,readonly:kc,promise:Dp,optional:Oc,lazy:jc};function Dn(e,t){if("_idmap"in e){let n=e,o=jr({...t,processors:ic}),i={};for(let s of n._idmap.entries()){let[l,m]=s;be(m,o)}let a={},c={registry:n,uri:t?.uri,defs:i};o.external=c;for(let s of n._idmap.entries()){let[l,m]=s;Nr(o,m),a[l]=xr(o,m)}if(Object.keys(i).length>0){let s=o.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[s]:i}}return{schemas:a}}let r=jr({...t,processors:ic});return be(e,r),Nr(r,e),xr(r,e)}var lt={};$s(lt,{ZodISODate:()=>Cc,ZodISODateTime:()=>Nc,ZodISODuration:()=>Uc,ZodISOTime:()=>qc,date:()=>Ac,datetime:()=>xc,duration:()=>Lc,time:()=>Mc});var Nc=q("ZodISODateTime",(e,t)=>{tm.init(e,t),Ee.init(e,t)});function xc(e){return dp(Nc,e)}var Cc=q("ZodISODate",(e,t)=>{rm.init(e,t),Ee.init(e,t)});function Ac(e){return mp(Cc,e)}var qc=q("ZodISOTime",(e,t)=>{nm.init(e,t),Ee.init(e,t)});function Mc(e){return pp(qc,e)}var Uc=q("ZodISODuration",(e,t)=>{om.init(e,t),Ee.init(e,t)});function Lc(e){return fp(Uc,e)}var Zp=(e,t)=>{Ko.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>xs(e,r)},flatten:{value:r=>Ns(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Er,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Er,2)}},isEmpty:{get(){return e.issues.length===0}}})},y0=q("ZodError",Zp),rt=q("ZodError",Zp,{Parent:Error});var Fp=Go(rt),Hp=Wo(rt),ti=Nn(rt),Jp=xn(rt),Bp=Ml(rt),Kp=Ul(rt),Gp=Ll(rt),Wp=Dl(rt),Yp=Vl(rt),Xp=Zl(rt),Qp=Fl(rt),ef=Hl(rt);var $e=q("ZodType",(e,t)=>(ye.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ln(e,"input"),output:Ln(e,"output")}}),e.toJSONSchema=Pp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(J.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]})),e.clone=(r,n)=>it(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Fp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>ti(e,r,n),e.parseAsync=async(r,n)=>Hp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Jp(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Bp(e,r,n),e.decode=(r,n)=>Kp(e,r,n),e.encodeAsync=async(r,n)=>Gp(e,r,n),e.decodeAsync=async(r,n)=>Wp(e,r,n),e.safeEncode=(r,n)=>Yp(e,r,n),e.safeDecode=(r,n)=>Xp(e,r,n),e.safeEncodeAsync=async(r,n)=>Qp(e,r,n),e.safeDecodeAsync=async(r,n)=>ef(e,r,n),e.refine=(r,n)=>e.check(f_(r,n)),e.superRefine=r=>e.check(h_(r)),e.overwrite=r=>e.check(At(r)),e.optional=()=>Q(e),e.nullable=()=>Vc(e),e.nullish=()=>Q(Vc(e)),e.nonoptional=r=>s_(e,r),e.array=()=>O(e),e.or=r=>W([e,r]),e.and=r=>gt(e,r),e.transform=r=>Zc(e,mf(r)),e.default=r=>o_(e,r),e.prefault=r=>a_(e,r),e.catch=r=>u_(e,r),e.pipe=r=>Zc(e,r),e.readonly=()=>hf(e),e.describe=r=>{let n=e.clone();return bt.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return bt.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return bt.get(e);let n=e.clone();return bt.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),nf=q("_ZodString",(e,t)=>{qn.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>ac(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Ks(...n)),e.includes=(...n)=>e.check(Ys(...n)),e.startsWith=(...n)=>e.check(Xs(...n)),e.endsWith=(...n)=>e.check(Qs(...n)),e.min=(...n)=>e.check(or(...n)),e.max=(...n)=>e.check(Un(...n)),e.length=(...n)=>e.check(ei(...n)),e.nonempty=(...n)=>e.check(or(1,...n)),e.lowercase=n=>e.check(Gs(n)),e.uppercase=n=>e.check(Ws(n)),e.trim=()=>e.check(tc()),e.normalize=(...n)=>e.check(ec(...n)),e.toLowerCase=()=>e.check(rc()),e.toUpperCase=()=>e.check(nc()),e.slugify=()=>e.check(oc())}),Fc=q("ZodString",(e,t)=>{qn.init(e,t),nf.init(e,t),e.email=r=>e.check(Hs(of,r)),e.url=r=>e.check(Bs(af,r)),e.jwt=r=>e.check(lp(Fv,r)),e.emoji=r=>e.check(Wm(kv,r)),e.guid=r=>e.check(Js(tf,r)),e.uuid=r=>e.check(Jm(ri,r)),e.uuidv4=r=>e.check(Bm(ri,r)),e.uuidv6=r=>e.check(Km(ri,r)),e.uuidv7=r=>e.check(Gm(ri,r)),e.nanoid=r=>e.check(Ym(Ov,r)),e.guid=r=>e.check(Js(tf,r)),e.cuid=r=>e.check(Xm(jv,r)),e.cuid2=r=>e.check(Qm(Nv,r)),e.ulid=r=>e.check(ep(xv,r)),e.base64=r=>e.check(sp(Dv,r)),e.base64url=r=>e.check(cp(Vv,r)),e.xid=r=>e.check(tp(Cv,r)),e.ksuid=r=>e.check(rp(Av,r)),e.ipv4=r=>e.check(np(qv,r)),e.ipv6=r=>e.check(op(Mv,r)),e.cidrv4=r=>e.check(ip(Uv,r)),e.cidrv6=r=>e.check(ap(Lv,r)),e.e164=r=>e.check(up(Zv,r)),e.datetime=r=>e.check(xc(r)),e.date=r=>e.check(Ac(r)),e.time=r=>e.check(Mc(r)),e.duration=r=>e.check(Lc(r))});function u(e){return Fm(Fc,e)}var Ee=q("ZodStringFormat",(e,t)=>{we.init(e,t),nf.init(e,t)}),of=q("ZodEmail",(e,t)=>{Jd.init(e,t),Ee.init(e,t)});function Hc(e){return Hs(of,e)}var tf=q("ZodGUID",(e,t)=>{Fd.init(e,t),Ee.init(e,t)});var ri=q("ZodUUID",(e,t)=>{Hd.init(e,t),Ee.init(e,t)});var af=q("ZodURL",(e,t)=>{Bd.init(e,t),Ee.init(e,t)});function Vn(e){return Bs(af,e)}var kv=q("ZodEmoji",(e,t)=>{Kd.init(e,t),Ee.init(e,t)});var Ov=q("ZodNanoID",(e,t)=>{Gd.init(e,t),Ee.init(e,t)});var jv=q("ZodCUID",(e,t)=>{Wd.init(e,t),Ee.init(e,t)});var Nv=q("ZodCUID2",(e,t)=>{Yd.init(e,t),Ee.init(e,t)});var xv=q("ZodULID",(e,t)=>{Xd.init(e,t),Ee.init(e,t)});var Cv=q("ZodXID",(e,t)=>{Qd.init(e,t),Ee.init(e,t)});var Av=q("ZodKSUID",(e,t)=>{em.init(e,t),Ee.init(e,t)});var qv=q("ZodIPv4",(e,t)=>{im.init(e,t),Ee.init(e,t)});var Mv=q("ZodIPv6",(e,t)=>{am.init(e,t),Ee.init(e,t)});var Uv=q("ZodCIDRv4",(e,t)=>{sm.init(e,t),Ee.init(e,t)});var Lv=q("ZodCIDRv6",(e,t)=>{cm.init(e,t),Ee.init(e,t)});var Dv=q("ZodBase64",(e,t)=>{lm.init(e,t),Ee.init(e,t)});var Vv=q("ZodBase64URL",(e,t)=>{dm.init(e,t),Ee.init(e,t)});var Zv=q("ZodE164",(e,t)=>{mm.init(e,t),Ee.init(e,t)});var Fv=q("ZodJWT",(e,t)=>{pm.init(e,t),Ee.init(e,t)});var ni=q("ZodNumber",(e,t)=>{Ls.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>sc(e,n,o,i),e.gt=(n,o)=>e.check(Or(n,o)),e.gte=(n,o)=>e.check(ut(n,o)),e.min=(n,o)=>e.check(ut(n,o)),e.lt=(n,o)=>e.check(kr(n,o)),e.lte=(n,o)=>e.check($t(n,o)),e.max=(n,o)=>e.check($t(n,o)),e.int=n=>e.check(rf(n)),e.safe=n=>e.check(rf(n)),e.positive=n=>e.check(Or(0,n)),e.nonnegative=n=>e.check(ut(0,n)),e.negative=n=>e.check(kr(0,n)),e.nonpositive=n=>e.check($t(0,n)),e.multipleOf=(n,o)=>e.check(Mn(n,o)),e.step=(n,o)=>e.check(Mn(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Z(e){return hp(ni,e)}var Hv=q("ZodNumberFormat",(e,t)=>{fm.init(e,t),ni.init(e,t)});function rf(e){return vp(Hv,e)}var Jc=q("ZodBoolean",(e,t)=>{Ds.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cc(e,r,n,o)});function G(e){return _p(Jc,e)}var sf=q("ZodBigInt",(e,t)=>{hm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>uc(e,n,o,i),e.gte=(n,o)=>e.check(ut(n,o)),e.min=(n,o)=>e.check(ut(n,o)),e.gt=(n,o)=>e.check(Or(n,o)),e.gte=(n,o)=>e.check(ut(n,o)),e.min=(n,o)=>e.check(ut(n,o)),e.lt=(n,o)=>e.check(kr(n,o)),e.lte=(n,o)=>e.check($t(n,o)),e.max=(n,o)=>e.check($t(n,o)),e.positive=n=>e.check(Or(BigInt(0),n)),e.negative=n=>e.check(kr(BigInt(0),n)),e.nonpositive=n=>e.check($t(BigInt(0),n)),e.nonnegative=n=>e.check(ut(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(Mn(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var Jv=q("ZodNull",(e,t)=>{gm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lc(e,r,n,o)});function qt(e){return bp(Jv,e)}var Bv=q("ZodAny",(e,t)=>{vm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mc(e,r,n,o)});function Bc(){return $p(Bv)}var Kv=q("ZodUnknown",(e,t)=>{_m.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pc(e,r,n,o)});function ee(){return zp(Kv)}var Gv=q("ZodNever",(e,t)=>{Sm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dc(e,r,n,o)});function cf(e){return Rp(Gv,e)}var uf=q("ZodDate",(e,t)=>{ym.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>fc(e,n,o,i),e.min=(n,o)=>e.check(ut(n,o)),e.max=(n,o)=>e.check($t(n,o));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var Wv=q("ZodArray",(e,t)=>{bm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Sc(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(or(r,n)),e.nonempty=r=>e.check(or(1,r)),e.max=(r,n)=>e.check(Un(r,n)),e.length=(r,n)=>e.check(ei(r,n)),e.unwrap=()=>e.element});function O(e,t){return Tp(Wv,e,t)}var lf=q("ZodObject",(e,t)=>{Rm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yc(e,r,n,o),J.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>se(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ee()}),e.loose=()=>e.clone({...e._zod.def,catchall:ee()}),e.strict=()=>e.clone({...e._zod.def,catchall:cf()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>J.extend(e,r),e.safeExtend=r=>J.safeExtend(e,r),e.merge=r=>J.merge(e,r),e.pick=r=>J.pick(e,r),e.omit=r=>J.omit(e,r),e.partial=(...r)=>J.partial(pf,e,r[0]),e.required=(...r)=>J.required(ff,e,r[0])});function E(e,t){let r={type:"object",shape:e??{},...J.normalizeParams(t)};return new lf(r)}function ne(e,t){return new lf({type:"object",shape:e,catchall:ee(),...J.normalizeParams(t)})}var df=q("ZodUnion",(e,t)=>{Vs.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bc(e,r,n,o),e.options=t.options});function W(e,t){return new df({type:"union",options:e,...J.normalizeParams(t)})}var Yv=q("ZodDiscriminatedUnion",(e,t)=>{df.init(e,t),wm.init(e,t)});function Cr(e,t,r){return new Yv({type:"union",options:t,discriminator:e,...J.normalizeParams(r)})}var Xv=q("ZodIntersection",(e,t)=>{Tm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$c(e,r,n,o)});function gt(e,t){return new Xv({type:"intersection",left:e,right:t})}var Qv=q("ZodRecord",(e,t)=>{Em.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zc(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function B(e,t,r){return new Qv({type:"record",keyType:e,valueType:t,...J.normalizeParams(r)})}var Dc=q("ZodEnum",(e,t)=>{Im.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>hc(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Dc({...t,checks:[],...J.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Dc({...t,checks:[],...J.normalizeParams(o),entries:i})}});function se(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Dc({type:"enum",entries:r,...J.normalizeParams(t)})}var e_=q("ZodLiteral",(e,t)=>{Pm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gc(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function j(e,t){return new e_({type:"literal",values:Array.isArray(e)?e:[e],...J.normalizeParams(t)})}var t_=q("ZodTransform",(e,t)=>{km.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_c(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Tr(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(J.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(J.issue(a))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function mf(e){return new t_({type:"transform",transform:e})}var pf=q("ZodOptional",(e,t)=>{Om.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Oc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Q(e){return new pf({type:"optional",innerType:e})}var r_=q("ZodNullable",(e,t)=>{jm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Rc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Vc(e){return new r_({type:"nullable",innerType:e})}var n_=q("ZodDefault",(e,t)=>{Nm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Tc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function o_(e,t){return new n_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var i_=q("ZodPrefault",(e,t)=>{xm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ec(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function a_(e,t){return new i_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var ff=q("ZodNonOptional",(e,t)=>{Cm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>wc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function s_(e,t){return new ff({type:"nonoptional",innerType:e,...J.normalizeParams(t)})}var c_=q("ZodCatch",(e,t)=>{Am.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ic(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function u_(e,t){return new c_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var l_=q("ZodPipe",(e,t)=>{qm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Pc(e,r,n,o),e.in=t.in,e.out=t.out});function Zc(e,t){return new l_({type:"pipe",in:e,out:t})}var d_=q("ZodReadonly",(e,t)=>{Mm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function hf(e){return new d_({type:"readonly",innerType:e})}var m_=q("ZodLazy",(e,t)=>{Um.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jc(e,r,n,o),e.unwrap=()=>e._zod.def.getter()});function Ar(e){return new m_({type:"lazy",getter:e})}var p_=q("ZodCustom",(e,t)=>{Lm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vc(e,r,n,o)});function f_(e,t={}){return Ep(p_,e,t)}function h_(e){return Ip(e)}function ar(e,t){return Zc(mf(e),t)}var vf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var gf;gf||(gf={});var oi={};$s(oi,{bigint:()=>y_,boolean:()=>S_,date:()=>b_,number:()=>__,string:()=>v_});function v_(e){return Hm(Fc,e)}function __(e){return gp(ni,e)}function S_(e){return Sp(Jc,e)}function y_(e){return yp(sf,e)}function b_(e){return wp(uf,e)}We(Zs());var cr="2025-11-25";var ii=[cr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ai="io.modelcontextprotocol/related-task",ur="io.modelcontextprotocol/protocolVersion",qr="io.modelcontextprotocol/clientInfo",Rt="io.modelcontextprotocol/serverInfo",wt="io.modelcontextprotocol/clientCapabilities",Zn="io.modelcontextprotocol/subscriptionId",Ut="io.modelcontextprotocol/logLevel";var lr="2.0";var Mt=Ar(()=>W([u(),Z(),G(),qt(),B(u(),Mt),O(Mt)])),ke=B(u(),Mt),Wc=O(Mt),Fn=W([u(),Z().int()]),Hn=u(),si=E({ttl:Z().optional()}),ci=E({taskId:u()}),Jn=ne({progressToken:Fn.optional(),[ai]:ci.optional()}),De=E({_meta:Jn.optional()}),dr=De.extend({task:si.optional()}),Oe=E({method:u(),params:De.loose().optional()}),Be=E({_meta:Jn.optional()}),Ke=E({method:u(),params:Be.loose().optional()}),Bn=ne({get[Rt](){return Lr.optional().catch(void 0)}}),je=ne({_meta:Bn.optional()}),Lt=W([u(),Z().int()]),Kn=E({jsonrpc:j(lr),id:Lt,...Oe.shape}).strict(),Gn=E({jsonrpc:j(lr),...Ke.shape}).strict(),Mr=E({jsonrpc:j(lr),id:Lt,result:je}).strict(),Ur=E({jsonrpc:j(lr),id:Lt.optional(),error:E({code:Z().int(),message:u(),data:ee().optional()})}).strict(),Wn=W([Kn,Gn,Mr,Ur]),Yc=W([Mr,Ur]),Yn=je.strict(),ui=Be.extend({requestId:Lt.optional(),reason:u().optional()}),Xn=Ke.extend({method:j("notifications/cancelled"),params:ui}),li=E({src:u(),mimeType:u().optional(),sizes:O(u()).optional(),theme:se(["light","dark"]).optional()}),Dt=E({icons:O(li).optional()}),zt=E({name:u(),title:u().optional()}),Lr=zt.extend({...zt.shape,...Dt.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),z_=gt(E({applyDefaults:G().optional()}),ke),R_=ar(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,gt(E({form:z_.optional(),url:ke.optional()}),ke.optional())),di=ne({list:ke.optional(),cancel:ke.optional(),requests:ne({sampling:ne({createMessage:ke.optional()}).optional(),elicitation:ne({create:ke.optional()}).optional()}).optional()}),mi=ne({list:ke.optional(),cancel:ke.optional(),requests:ne({tools:ne({call:ke.optional()}).optional()}).optional()}),pi=E({experimental:B(u(),ke).optional(),sampling:E({context:ke.optional(),tools:ke.optional()}).optional(),elicitation:R_.optional(),roots:E({listChanged:G().optional()}).optional(),tasks:di.optional(),extensions:B(u(),ke).optional()}),fi=De.extend({protocolVersion:u(),capabilities:pi,clientInfo:Lr}),hi=Oe.extend({method:j("initialize"),params:fi}),Qn=E({experimental:B(u(),ke).optional(),logging:ke.optional(),completions:ke.optional(),prompts:E({listChanged:G().optional()}).optional(),resources:E({subscribe:G().optional(),listChanged:G().optional()}).optional(),tools:E({listChanged:G().optional()}).optional(),tasks:mi.optional(),extensions:B(u(),ke).optional()}),gi=je.extend({protocolVersion:u(),capabilities:Qn,serverInfo:Lr,instructions:u().optional()}),vi=Ke.extend({method:j("notifications/initialized"),params:Be.optional()}),_i=Oe.extend({method:j("server/discover"),params:De.optional()}),Si=je.extend({supportedVersions:O(u()),capabilities:Qn,instructions:u().optional()}),eo=Oe.extend({method:j("ping"),params:De.optional()}),yi=E({progress:Z(),total:Q(Z()),message:Q(u())}),bi=E({...Be.shape,...yi.shape,progressToken:Fn}),to=Ke.extend({method:j("notifications/progress"),params:bi}),$i=De.extend({cursor:Hn.optional()}),Vt=Oe.extend({params:$i.optional()}),Zt=je.extend({nextCursor:Hn.optional()}),ro=E({uri:u(),mimeType:Q(u()),_meta:B(u(),ee()).optional()}),no=ro.extend({text:u()}),Xc=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),oo=ro.extend({blob:Xc}),Ft=se(["user","assistant"]),Tt=E({audience:O(Ft).optional(),priority:Z().min(0).max(1).optional(),lastModified:lt.datetime({offset:!0}).optional()}),io=E({...zt.shape,...Dt.shape,uri:u(),description:Q(u()),mimeType:Q(u()),size:Q(Z()),annotations:Tt.optional(),_meta:Q(ne({}))}),zi=E({...zt.shape,...Dt.shape,uriTemplate:u(),description:Q(u()),mimeType:Q(u()),annotations:Tt.optional(),_meta:Q(ne({}))}),Ri=Vt.extend({method:j("resources/list")}),wi=Zt.extend({resources:O(io)}),Ti=Vt.extend({method:j("resources/templates/list")}),Ei=Zt.extend({resourceTemplates:O(zi)}),Dr=De.extend({uri:u()}),Ii=Dr,Pi=Oe.extend({method:j("resources/read"),params:Ii}),ki=je.extend({contents:O(W([no,oo]))}),Oi=Ke.extend({method:j("notifications/resources/list_changed"),params:Be.optional()}),ji=Dr,Ni=Oe.extend({method:j("resources/subscribe"),params:ji}),xi=Dr,Ci=Oe.extend({method:j("resources/unsubscribe"),params:xi}),ao=E({toolsListChanged:G().optional(),promptsListChanged:G().optional(),resourcesListChanged:G().optional(),resourceSubscriptions:O(u()).optional()}),Ai=De.extend({notifications:ao}),qi=Oe.extend({method:j("subscriptions/listen"),params:Ai}),Mi=Be.extend({notifications:ao}),Ui=Ke.extend({method:j("notifications/subscriptions/acknowledged"),params:Mi}),Li=Bn.extend({[Zn]:Lt}),Di=je.extend({_meta:Li}),Vi=Be.extend({uri:u()}),Zi=Ke.extend({method:j("notifications/resources/updated"),params:Vi}),Fi=E({name:u(),description:Q(u()),required:Q(G())}),Hi=E({...zt.shape,...Dt.shape,description:Q(u()),arguments:Q(O(Fi)),_meta:Q(ne({}))}),Ji=Vt.extend({method:j("prompts/list")}),Bi=Zt.extend({prompts:O(Hi)}),Ki=De.extend({name:u(),arguments:B(u(),u()).optional()}),Gi=Oe.extend({method:j("prompts/get"),params:Ki}),Vr=E({type:j("text"),text:u(),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Zr=E({type:j("image"),data:Xc,mimeType:u(),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Fr=E({type:j("audio"),data:Xc,mimeType:u(),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Wi=E({type:j("tool_use"),name:u(),id:u(),input:B(u(),ee()),_meta:B(u(),ee()).optional()}),Yi=E({type:j("resource"),resource:W([no,oo]),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Xi=io.extend({type:j("resource_link")}),Hr=W([Vr,Zr,Fr,Xi,Yi]),Qi=E({role:Ft,content:Hr}),ea=je.extend({description:u().optional(),messages:O(Qi)}),ta=Ke.extend({method:j("notifications/prompts/list_changed"),params:Be.optional()}),ra=E({title:u().optional(),readOnlyHint:G().optional(),destructiveHint:G().optional(),idempotentHint:G().optional(),openWorldHint:G().optional()}),na=E({taskSupport:se(["required","optional","forbidden"]).optional()}),so=E({...zt.shape,...Dt.shape,description:u().optional(),inputSchema:E({type:j("object"),properties:B(u(),Mt).optional(),required:O(u()).optional()}).catchall(ee()),outputSchema:ne({$schema:u().optional()}).optional(),annotations:ra.optional(),execution:na.optional(),_meta:B(u(),ee()).optional()}),oa=Vt.extend({method:j("tools/list")}),ia=Zt.extend({tools:O(so)}),co=je.extend({content:O(Hr).default([]),structuredContent:ee().optional(),isError:G().optional()}),Qc=co.or(je.extend({toolResult:ee()})),aa=dr.extend({name:u(),arguments:B(u(),ee()).optional()}),sa=Oe.extend({method:j("tools/call"),params:aa}),ca=Ke.extend({method:j("notifications/tools/list_changed"),params:Be.optional()}),eu=E({autoRefresh:G().default(!0),debounceMs:Z().int().nonnegative().default(300)}),Ht=se(["debug","info","notice","warning","error","critical","alert","emergency"]),ua=De.extend({level:Ht}),la=Oe.extend({method:j("logging/setLevel"),params:ua}),da=Be.extend({level:Ht,logger:u().optional(),data:ee()}),ma=Ke.extend({method:j("notifications/message"),params:da}),pa=E({name:u().optional()}),fa=E({hints:O(pa).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),ha=E({mode:se(["auto","required","none"]).optional()}),ga=E({type:j("tool_result"),toolUseId:u().describe("The unique identifier for the corresponding tool call."),content:O(Hr),structuredContent:ee().optional(),isError:G().optional(),_meta:B(u(),ee()).optional()}),va=Cr("type",[Vr,Zr,Fr]),sr=Cr("type",[Vr,Zr,Fr,Wi,ga]),_a=E({role:Ft,content:W([sr,O(sr)]),_meta:B(u(),ee()).optional()}),Sa=dr.extend({messages:O(_a),modelPreferences:fa.optional(),systemPrompt:u().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:O(u()).optional(),metadata:ke.optional(),tools:O(so).optional(),toolChoice:ha.optional()}),ya=Oe.extend({method:j("sampling/createMessage"),params:Sa}),ba=je.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens"]).or(u())),role:Ft,content:va}),$a=je.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens","toolUse"]).or(u())),role:Ft,content:W([sr,O(sr)])}),uo=E({type:j("boolean"),title:u().optional(),description:u().optional(),default:G().optional()}),Jr=E({type:j("string"),title:u().optional(),description:u().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:se(["email","uri","date","date-time"]).optional(),default:u().optional()}),Br=E({type:se(["number","integer"]),title:u().optional(),description:u().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),lo=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),default:u().optional()}),mo=E({type:j("string"),title:u().optional(),description:u().optional(),oneOf:O(E({const:u(),title:u()})),default:u().optional()}),po=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),enumNames:O(u()).optional(),default:u().optional()}),za=W([lo,mo]),fo=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({type:j("string"),enum:O(u())}),default:O(u()).optional()}),ho=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({anyOf:O(E({const:u(),title:u()}))}),default:O(u()).optional()}),Ra=W([fo,ho]),wa=W([po,za,Ra]),go=W([wa,uo,Jr,Br]),Kr=dr.extend({mode:j("form").optional(),message:u(),requestedSchema:E({type:j("object"),properties:B(u(),go),required:O(u()).optional()}).catchall(ee())}),Ta=dr.extend({mode:j("url"),message:u(),elicitationId:u(),url:u().url()}),Ea=W([Kr,Ta]),Ia=Oe.extend({method:j("elicitation/create"),params:Ea}),Pa=Be.extend({elicitationId:u()}),ka=Ke.extend({method:j("notifications/elicitation/complete"),params:Pa}),Oa=je.extend({action:se(["accept","decline","cancel"]),content:ar(e=>e===null?void 0:e,B(u(),W([u(),Z(),G(),O(u())])).optional())}),ja=E({type:j("ref/resource"),uri:u()}),Na=E({type:j("ref/prompt"),name:u()}),xa=De.extend({ref:W([Na,ja]),argument:E({name:u(),value:u()}),context:E({arguments:B(u(),u()).optional()}).optional()}),Ca=Oe.extend({method:j("completion/complete"),params:xa}),Aa=je.extend({completion:ne({values:O(u()).max(100),total:Q(Z().int()),hasMore:Q(G())})}),qa=E({uri:u().startsWith("file://"),name:u().optional(),_meta:B(u(),ee()).optional()}),Ma=Oe.extend({method:j("roots/list"),params:De.optional()}),Ua=je.extend({roots:O(qa)}),La=Ke.extend({method:j("notifications/roots/list_changed"),params:Be.optional()}),tu=ne({ttl:Z().optional(),pollInterval:Z().optional()}),Da=se(["working","input_required","completed","failed","cancelled"]),Jt=E({taskId:u(),status:Da,ttl:W([Z(),qt()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:Q(Z()),statusMessage:Q(u())}),ru=je.extend({task:Jt}),Va=Be.merge(Jt),nu=Ke.extend({method:j("notifications/tasks/status"),params:Va}),ou=Oe.extend({method:j("tasks/get"),params:De.extend({taskId:u()})}),iu=je.merge(Jt),au=Oe.extend({method:j("tasks/result"),params:De.extend({taskId:u()})}),su=je.loose(),cu=Vt.extend({method:j("tasks/list")}),uu=Zt.extend({tasks:O(Jt)}),lu=Oe.extend({method:j("tasks/cancel"),params:De.extend({taskId:u()})}),du=je.merge(Jt),mu=W([eo,hi,_i,Ca,la,Gi,Ji,Ri,Ti,Pi,Ni,Ci,qi,sa,oa]),pu=W([Xn,to,vi,La]),fu=W([Yn,ba,$a,Oa,Ua]),hu=W([eo,ya,Ia,Ma]),gu=W([Xn,to,ma,Zi,Oi,ca,ta,Ui,ka]),vu=W([Yn,gi,Si,Aa,ea,Bi,wi,Ei,ki,co,ia,Di]),Le=Vn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:vf.custom,message:"URL must be parseable",fatal:!0}),zs}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),_u=ne({resource:u().url(),authorization_servers:O(Le).optional(),jwks_uri:u().url().optional(),scopes_supported:O(u()).optional(),bearer_methods_supported:O(u()).optional(),resource_signing_alg_values_supported:O(u()).optional(),resource_name:u().optional(),resource_documentation:u().optional(),resource_policy_uri:u().url().optional(),resource_tos_uri:u().url().optional(),tls_client_certificate_bound_access_tokens:G().optional(),authorization_details_types_supported:O(u()).optional(),dpop_signing_alg_values_supported:O(u()).optional(),dpop_bound_access_tokens_required:G().optional()}),Za=ne({issuer:u(),authorization_endpoint:Le,token_endpoint:Le,registration_endpoint:Le.optional(),scopes_supported:O(u()).optional(),response_types_supported:O(u()),response_modes_supported:O(u()).optional(),grant_types_supported:O(u()).optional(),token_endpoint_auth_methods_supported:O(u()).optional(),token_endpoint_auth_signing_alg_values_supported:O(u()).optional(),service_documentation:Le.optional(),revocation_endpoint:Le.optional(),revocation_endpoint_auth_methods_supported:O(u()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O(u()).optional(),introspection_endpoint:u().optional(),introspection_endpoint_auth_methods_supported:O(u()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O(u()).optional(),code_challenge_methods_supported:O(u()).optional(),client_id_metadata_document_supported:G().optional(),authorization_response_iss_parameter_supported:G().optional().catch(void 0)}),Fa=ne({issuer:u(),authorization_endpoint:Le,token_endpoint:Le,userinfo_endpoint:Le.optional(),jwks_uri:Le,registration_endpoint:Le.optional(),scopes_supported:O(u()).optional(),response_types_supported:O(u()),response_modes_supported:O(u()).optional(),grant_types_supported:O(u()).optional(),acr_values_supported:O(u()).optional(),subject_types_supported:O(u()),id_token_signing_alg_values_supported:O(u()),id_token_encryption_alg_values_supported:O(u()).optional(),id_token_encryption_enc_values_supported:O(u()).optional(),userinfo_signing_alg_values_supported:O(u()).optional(),userinfo_encryption_alg_values_supported:O(u()).optional(),userinfo_encryption_enc_values_supported:O(u()).optional(),request_object_signing_alg_values_supported:O(u()).optional(),request_object_encryption_alg_values_supported:O(u()).optional(),request_object_encryption_enc_values_supported:O(u()).optional(),token_endpoint_auth_methods_supported:O(u()).optional(),token_endpoint_auth_signing_alg_values_supported:O(u()).optional(),display_values_supported:O(u()).optional(),claim_types_supported:O(u()).optional(),claims_supported:O(u()).optional(),service_documentation:u().optional(),claims_locales_supported:O(u()).optional(),ui_locales_supported:O(u()).optional(),claims_parameter_supported:G().optional(),request_parameter_supported:G().optional(),request_uri_parameter_supported:G().optional(),require_request_uri_registration:G().optional(),op_policy_uri:Le.optional(),op_tos_uri:Le.optional(),client_id_metadata_document_supported:G().optional(),authorization_response_iss_parameter_supported:G().optional().catch(void 0)}),Su=E({...Fa.shape,...Za.pick({code_challenge_methods_supported:!0}).shape}),yu=E({access_token:u(),id_token:u().optional(),token_type:u(),expires_in:oi.number().optional(),scope:u().optional(),refresh_token:u().optional()}).strip(),bu=E({issued_token_type:j("urn:ietf:params:oauth:token-type:id-jag"),access_token:u(),token_type:u().optional(),expires_in:Z().optional(),scope:u().optional()}).strip(),$u=E({error:u(),error_description:u().optional(),error_uri:u().optional()}),Gc=Le.optional().or(j("").transform(()=>{})),Ha=E({redirect_uris:O(Le),token_endpoint_auth_method:u().optional(),grant_types:O(u()).optional(),response_types:O(u()).optional(),application_type:u().optional(),client_name:u().optional(),client_uri:Le.optional(),logo_uri:Gc,scope:u().optional(),contacts:O(u()).optional(),tos_uri:Gc,policy_uri:u().optional(),jwks_uri:Le.optional(),jwks:Bc().optional(),software_id:u().optional(),software_version:u().optional(),software_statement:u().optional()}).strip(),Ja=E({client_id:u(),client_secret:u().optional(),client_id_issued_at:Z().optional(),client_secret_expires_at:Z().optional()}).strip(),zu=Ha.merge(Ja),Ru=E({error:u(),error_description:u().optional()}).strip(),wu=E({token:u(),token_type_hint:u().optional()}).strip();var ku=Symbol.for("mcp.sdk.errorBrands");function Cu(e,t){let r=new Set,n=t;for(;typeof n=="function";){let o=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof o=="string"&&r.add(o),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,ku,{value:r,enumerable:!1,configurable:!0})}function Wr(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,ku)){let r=t[ku];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var w_=class Uf extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Wr(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Wr(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",Cu(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new Uf(t.error,t.error_description??t.error,t.error_uri)}},he=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),le=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Wr(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Wr(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",Cu(this,new.target)}},T_=class extends le{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r){super(e,t,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Ef(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function E_(e,t,r){return e==="elicitation"&&t==="form"&&r.form===void 0&&r.url===void 0}function Lf(e){switch(e.method){case"elicitation/create":return e.params?.mode==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function es(e,t){let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=t===void 0?void 0:t[n];if(i===void 0){r[n]=o;continue}if(Ef(o)&&Ef(i)){let a={};for(let[c,s]of Object.entries(o))s!==void 0&&i[c]===void 0&&!E_(n,c,i)&&(a[c]=s);Object.keys(a).length>0&&(r[n]=a)}}return Object.keys(r).length>0?r:void 0}var I_="2026-07-28";function $o(e){return e>=I_}function Df(e){return e.filter(t=>!$o(t))}function Au(e){return e.filter(t=>$o(t))}function Vf(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Zf=["task","inputRequests","requestState"];function qu(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Zf.some(t=>t in e)?e:{...e,content:[]}}function P_(){let e=Ar(()=>W([u(),Z(),G(),qt(),B(u(),e),O(e)])),t=B(u(),e),r=W([u(),Z().int()]),n=u(),o=E({ttl:Z().optional()}),i=E({taskId:u()}),a=ne({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=E({_meta:a.optional()}),s=c.extend({task:o.optional()}),l=E({method:u(),params:c.loose().optional()}),m=E({_meta:a.optional()}),h=E({method:u(),params:m.loose().optional()}),z=ne({_meta:a.optional()}),R=W([u(),Z().int()]),v=z.strict(),b=m.extend({requestId:R.optional(),reason:u().optional()}),g=h.extend({method:j("notifications/cancelled"),params:b}),d=E({src:u(),mimeType:u().optional(),sizes:O(u()).optional(),theme:se(["light","dark"]).optional()}),_=E({icons:O(d).optional()}),p=E({name:u(),title:u().optional()}),S=p.extend({...p.shape,..._.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),w=gt(E({applyDefaults:G().optional()}),t),y=ar(Je=>Je&&typeof Je=="object"&&!Array.isArray(Je)&&Object.keys(Je).length===0?{form:{}}:Je,gt(E({form:w.optional(),url:t.optional()}),t.optional())),f=ne({list:t.optional(),cancel:t.optional(),requests:ne({sampling:ne({createMessage:t.optional()}).optional(),elicitation:ne({create:t.optional()}).optional()}).optional()}),T=ne({list:t.optional(),cancel:t.optional(),requests:ne({tools:ne({call:t.optional()}).optional()}).optional()}),A=E({experimental:B(u(),t).optional(),sampling:E({context:t.optional(),tools:t.optional()}).optional(),elicitation:y.optional(),roots:E({listChanged:G().optional()}).optional(),tasks:f.optional(),extensions:B(u(),t).optional()}),F=c.extend({protocolVersion:u(),capabilities:A,clientInfo:S}),M=l.extend({method:j("initialize"),params:F}),D=E({experimental:B(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:E({listChanged:G().optional()}).optional(),resources:E({subscribe:G().optional(),listChanged:G().optional()}).optional(),tools:E({listChanged:G().optional()}).optional(),tasks:T.optional(),extensions:B(u(),t).optional()}),Y=z.extend({protocolVersion:u(),capabilities:D,serverInfo:S,instructions:u().optional()}),K=h.extend({method:j("notifications/initialized"),params:m.optional()}),fe=l.extend({method:j("ping"),params:c.optional()}),Te=E({progress:Z(),total:Q(Z()),message:Q(u())}),ze=E({...m.shape,...Te.shape,progressToken:r}),Ce=h.extend({method:j("notifications/progress"),params:ze}),ve=c.extend({cursor:n.optional()}),k=l.extend({params:ve.optional()}),x=z.extend({nextCursor:n.optional()}),V=E({uri:u(),mimeType:Q(u()),_meta:B(u(),ee()).optional()}),$=V.extend({text:u()}),P=u().refine(Je=>{try{return atob(Je),!0}catch{return!1}},{message:"Invalid Base64 string"}),N=V.extend({blob:P}),H=se(["user","assistant"]),te=E({audience:O(H).optional(),priority:Z().min(0).max(1).optional(),lastModified:lt.datetime({offset:!0}).optional()}),pe=E({...p.shape,..._.shape,uri:u(),description:Q(u()),mimeType:Q(u()),size:Q(Z()),annotations:te.optional(),_meta:Q(ne({}))}),ae=E({...p.shape,..._.shape,uriTemplate:u(),description:Q(u()),mimeType:Q(u()),annotations:te.optional(),_meta:Q(ne({}))}),Re=k.extend({method:j("resources/list")}),Ge=x.extend({resources:O(pe)}),I=k.extend({method:j("resources/templates/list")}),C=x.extend({resourceTemplates:O(ae)}),U=c.extend({uri:u()}),oe=U,ie=l.extend({method:j("resources/read"),params:oe}),me=z.extend({contents:O(W([$,N]))}),Ne=h.extend({method:j("notifications/resources/list_changed"),params:m.optional()}),qe=U,Fe=l.extend({method:j("resources/subscribe"),params:qe}),Ae=U,Ie=l.extend({method:j("resources/unsubscribe"),params:Ae}),nt=m.extend({uri:u()}),Ue=h.extend({method:j("notifications/resources/updated"),params:nt}),_t=E({name:u(),description:Q(u()),required:Q(G())}),at=E({...p.shape,..._.shape,description:Q(u()),arguments:Q(O(_t)),_meta:Q(ne({}))}),St=k.extend({method:j("prompts/list")}),Et=x.extend({prompts:O(at)}),It=c.extend({name:u(),arguments:B(u(),u()).optional()}),Bt=l.extend({method:j("prompts/get"),params:It}),Kt=E({type:j("text"),text:u(),annotations:te.optional(),_meta:B(u(),ee()).optional()}),Gt=E({type:j("image"),data:P,mimeType:u(),annotations:te.optional(),_meta:B(u(),ee()).optional()}),Wt=E({type:j("audio"),data:P,mimeType:u(),annotations:te.optional(),_meta:B(u(),ee()).optional()}),en=E({type:j("tool_use"),name:u(),id:u(),input:B(u(),ee()),_meta:B(u(),ee()).optional()}),Pt=E({type:j("resource"),resource:W([$,N]),annotations:te.optional(),_meta:B(u(),ee()).optional()}),tn=pe.extend({type:j("resource_link")}),ot=W([Kt,Gt,Wt,tn,Pt]),hr=E({role:H,content:ot}),gr=z.extend({description:u().optional(),messages:O(hr)}),Yt=h.extend({method:j("notifications/prompts/list_changed"),params:m.optional()}),rn=E({title:u().optional(),readOnlyHint:G().optional(),destructiveHint:G().optional(),idempotentHint:G().optional(),openWorldHint:G().optional()}),vr=E({taskSupport:se(["required","optional","forbidden"]).optional()}),Xt=E({...p.shape,..._.shape,description:u().optional(),inputSchema:E({type:j("object"),properties:B(u(),e).optional(),required:O(u()).optional()}).catchall(ee()),outputSchema:E({type:j("object"),properties:B(u(),e).optional(),required:O(u()).optional()}).catchall(ee()).optional(),annotations:rn.optional(),execution:vr.optional(),_meta:B(u(),ee()).optional()}),_r=k.extend({method:j("tools/list")}),Sr=x.extend({tools:O(Xt)}),yr=z.extend({content:O(ot),structuredContent:B(u(),ee()).optional(),isError:G().optional()}),He=s.extend({name:u(),arguments:B(u(),ee()).optional()}),nn=l.extend({method:j("tools/call"),params:He}),To=h.extend({method:j("notifications/tools/list_changed"),params:m.optional()}),br=se(["debug","info","notice","warning","error","critical","alert","emergency"]),on=c.extend({level:br}),an=l.extend({method:j("logging/setLevel"),params:on}),sn=m.extend({level:br,logger:u().optional(),data:ee()}),cn=h.extend({method:j("notifications/message"),params:sn}),un=E({name:u().optional()}),ln=E({hints:O(un).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),dn=E({mode:se(["auto","required","none"]).optional()}),Eo=E({type:j("tool_result"),toolUseId:u().describe("The unique identifier for the corresponding tool call."),content:O(ot),structuredContent:E({}).loose().optional(),isError:G().optional(),_meta:B(u(),ee()).optional()}),mn=Cr("type",[Kt,Gt,Wt]),kt=Cr("type",[Kt,Gt,Wt,en,Eo]),pn=E({role:H,content:W([kt,O(kt)]),_meta:B(u(),ee()).optional()}),fn=s.extend({messages:O(pn),modelPreferences:ln.optional(),systemPrompt:u().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:O(u()).optional(),metadata:t.optional(),tools:O(Xt).optional(),toolChoice:dn.optional()}),hn=l.extend({method:j("sampling/createMessage"),params:fn}),gn=z.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens"]).or(u())),role:H,content:mn}),vn=z.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens","toolUse"]).or(u())),role:H,content:W([kt,O(kt)])}),_n=E({type:j("boolean"),title:u().optional(),description:u().optional(),default:G().optional()}),Sn=E({type:j("string"),title:u().optional(),description:u().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:se(["email","uri","date","date-time"]).optional(),default:u().optional()}),yn=E({type:se(["number","integer"]),title:u().optional(),description:u().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),bn=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),default:u().optional()}),$n=E({type:j("string"),title:u().optional(),description:u().optional(),oneOf:O(E({const:u(),title:u()})),default:u().optional()}),zn=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),enumNames:O(u()).optional(),default:u().optional()}),Rn=W([bn,$n]),Qt=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({type:j("string"),enum:O(u())}),default:O(u()).optional()}),er=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({anyOf:O(E({const:u(),title:u()}))}),default:O(u()).optional()}),Io=W([Qt,er]),Po=W([zn,Rn,Io]),et=W([Po,_n,Sn,yn]),tt=s.extend({mode:j("form").optional(),message:u(),requestedSchema:E({type:j("object"),properties:B(u(),et),required:O(u()).optional()}).catchall(ee())}),wn=s.extend({mode:j("url"),message:u(),elicitationId:u(),url:u().url()}),st=W([tt,wn]),ko=l.extend({method:j("elicitation/create"),params:st}),Oo=m.extend({elicitationId:u()}),jo=h.extend({method:j("notifications/elicitation/complete"),params:Oo}),No=z.extend({action:se(["accept","decline","cancel"]),content:ar(Je=>Je===null?void 0:Je,B(u(),W([u(),Z(),G(),O(u())])).optional())}),xo=E({type:j("ref/resource"),uri:u()}),Co=E({type:j("ref/prompt"),name:u()}),Ao=c.extend({ref:W([Co,xo]),argument:E({name:u(),value:u()}),context:E({arguments:B(u(),u()).optional()}).optional()}),Tn=l.extend({method:j("completion/complete"),params:Ao}),qo=z.extend({completion:ne({values:O(u()).max(100),total:Q(Z().int()),hasMore:Q(G())})}),Mo=E({uri:u().startsWith("file://"),name:u().optional(),_meta:B(u(),ee()).optional()}),$r=l.extend({method:j("roots/list"),params:c.optional()}),En=z.extend({roots:O(Mo)}),Uo=h.extend({method:j("notifications/roots/list_changed"),params:m.optional()}),Lo=ne({ttl:Z().optional(),pollInterval:Z().optional()}),Do=se(["working","input_required","completed","failed","cancelled"]),Ot=E({taskId:u(),status:Do,ttl:W([Z(),qt()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:Q(Z()),statusMessage:Q(u())}),Xe=z.extend({task:Ot}),Vo=m.merge(Ot),tr=h.extend({method:j("notifications/tasks/status"),params:Vo}),zr=l.extend({method:j("tasks/get"),params:c.extend({taskId:u()})}),Rr=z.merge(Ot),wr=l.extend({method:j("tasks/result"),params:c.extend({taskId:u()})}),bs=z.loose(),Qe=k.extend({method:j("tasks/list")}),xe=x.extend({tasks:O(Ot)}),rr=l.extend({method:j("tasks/cancel"),params:c.extend({taskId:u()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:o,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:s,RequestSchema:l,NotificationsParamsSchema:m,NotificationSchema:h,ResultSchema:z,RequestIdSchema:R,EmptyResultSchema:v,CancelledNotificationParamsSchema:b,CancelledNotificationSchema:g,IconSchema:d,IconsSchema:_,BaseMetadataSchema:p,ImplementationSchema:S,ClientTasksCapabilitySchema:f,ServerTasksCapabilitySchema:T,ClientCapabilitiesSchema:A,InitializeRequestParamsSchema:F,InitializeRequestSchema:M,ServerCapabilitiesSchema:D,InitializeResultSchema:Y,InitializedNotificationSchema:K,PingRequestSchema:fe,ProgressSchema:Te,ProgressNotificationParamsSchema:ze,ProgressNotificationSchema:Ce,PaginatedRequestParamsSchema:ve,PaginatedRequestSchema:k,PaginatedResultSchema:x,ResourceContentsSchema:V,TextResourceContentsSchema:$,BlobResourceContentsSchema:N,RoleSchema:H,AnnotationsSchema:te,ResourceSchema:pe,ResourceTemplateSchema:ae,ListResourcesRequestSchema:Re,ListResourcesResultSchema:Ge,ListResourceTemplatesRequestSchema:I,ListResourceTemplatesResultSchema:C,ResourceRequestParamsSchema:U,ReadResourceRequestParamsSchema:oe,ReadResourceRequestSchema:ie,ReadResourceResultSchema:me,ResourceListChangedNotificationSchema:Ne,SubscribeRequestParamsSchema:qe,SubscribeRequestSchema:Fe,UnsubscribeRequestParamsSchema:Ae,UnsubscribeRequestSchema:Ie,ResourceUpdatedNotificationParamsSchema:nt,ResourceUpdatedNotificationSchema:Ue,PromptArgumentSchema:_t,PromptSchema:at,ListPromptsRequestSchema:St,ListPromptsResultSchema:Et,GetPromptRequestParamsSchema:It,GetPromptRequestSchema:Bt,TextContentSchema:Kt,ImageContentSchema:Gt,AudioContentSchema:Wt,ToolUseContentSchema:en,EmbeddedResourceSchema:Pt,ResourceLinkSchema:tn,ContentBlockSchema:ot,PromptMessageSchema:hr,GetPromptResultSchema:gr,PromptListChangedNotificationSchema:Yt,ToolAnnotationsSchema:rn,ToolExecutionSchema:vr,ToolSchema:Xt,ListToolsRequestSchema:_r,ListToolsResultSchema:Sr,CallToolResultSchema:yr,CallToolRequestParamsSchema:He,CallToolRequestSchema:nn,ToolListChangedNotificationSchema:To,LoggingLevelSchema:br,SetLevelRequestParamsSchema:on,SetLevelRequestSchema:an,LoggingMessageNotificationParamsSchema:sn,LoggingMessageNotificationSchema:cn,ModelHintSchema:un,ModelPreferencesSchema:ln,ToolChoiceSchema:dn,ToolResultContentSchema:Eo,SamplingContentSchema:mn,SamplingMessageContentBlockSchema:kt,SamplingMessageSchema:pn,CreateMessageRequestParamsSchema:fn,CreateMessageRequestSchema:hn,CreateMessageResultSchema:gn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:_n,StringSchemaSchema:Sn,NumberSchemaSchema:yn,UntitledSingleSelectEnumSchemaSchema:bn,TitledSingleSelectEnumSchemaSchema:$n,LegacyTitledEnumSchemaSchema:zn,SingleSelectEnumSchemaSchema:Rn,UntitledMultiSelectEnumSchemaSchema:Qt,TitledMultiSelectEnumSchemaSchema:er,MultiSelectEnumSchemaSchema:Io,EnumSchemaSchema:Po,PrimitiveSchemaDefinitionSchema:et,ElicitRequestFormParamsSchema:tt,ElicitRequestURLParamsSchema:wn,ElicitRequestParamsSchema:st,ElicitRequestSchema:ko,ElicitationCompleteNotificationParamsSchema:Oo,ElicitationCompleteNotificationSchema:jo,ElicitResultSchema:No,ResourceTemplateReferenceSchema:xo,PromptReferenceSchema:Co,CompleteRequestParamsSchema:Ao,CompleteRequestSchema:Tn,CompleteResultSchema:qo,RootSchema:Mo,ListRootsRequestSchema:$r,ListRootsResultSchema:En,RootsListChangedNotificationSchema:Uo,TaskCreationParamsSchema:Lo,TaskStatusSchema:Do,TaskSchema:Ot,CreateTaskResultSchema:Xe,TaskStatusNotificationParamsSchema:Vo,TaskStatusNotificationSchema:tr,GetTaskRequestSchema:zr,GetTaskResultSchema:Rr,GetTaskPayloadRequestSchema:wr,GetTaskPayloadResultSchema:bs,ListTasksRequestSchema:Qe,ListTasksResultSchema:xe,CancelTaskRequestSchema:rr,CancelTaskResultSchema:z.merge(Ot),ClientRequestSchema:W([fe,M,Tn,an,Bt,St,Re,I,ie,Fe,Ie,nn,_r,zr,wr,Qe,rr]),ClientNotificationSchema:W([g,Ce,K,Uo,tr]),ClientResultSchema:W([v,gn,vn,No,En,Rr,xe,Xe]),ServerRequestSchema:W([fe,hn,ko,$r,zr,wr,Qe,rr]),ServerNotificationSchema:W([g,Ce,cn,Ue,Ne,To,Yt,tr,jo]),ServerResultSchema:W([v,Y,qo,gr,Et,Ge,C,me,yr,Sr,Rr,xe,Xe]),CallToolResultWireSchema:ee().superRefine((Je,Eg)=>{if(!(typeof Je!="object"||Je===null||Array.isArray(Je)||Je.content!==void 0)){for(let zl of Zf)if(zl in Je){Eg.addIssue({code:"custom",message:`content is required when the body carries '${zl}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(qu).pipe(yr)}}var k_;function Ff(){return k_??=P_()}function Hf(e){return e.type!=="object"}var O_=new Set(["const","enum","default","examples"]),j_=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function If(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function N_(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(If(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Tl(e.$schema)&&e.$recursiveAnchor!==!0,n=(o,i)=>{if(Array.isArray(o))return o.map(s=>n(s,!1));if(o===null||typeof o!="object"||!i&&If(o.$id))return o;let a={},c=!1;for(let[s,l]of Object.entries(o))i?a[s]=n(l,!1):(s==="$ref"||s==="$dynamicRef")&&typeof l=="string"?a[s]=l==="#"?"#/properties/result":l.startsWith("#/")?`#/properties/result${l.slice(1)}`:l:s==="$recursiveRef"&&l==="#"&&r?c=!0:O_.has(s)?a[s]=l:j_.has(s)?a[s]=n(l,!0):a[s]=n(l,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}var Jf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Bf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},x_={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ba;function Mu(){if(Ba)return Ba;let e=Ff();return Ba={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Ba}function Kf(e){return Object.prototype.hasOwnProperty.call(Jf,e)}function Gf(e){return Object.prototype.hasOwnProperty.call(Bf,e)}function C_(e){return Object.prototype.hasOwnProperty.call(x_,e)}function A_(e){return C_(e)?Mu().resultSchemas[e]:void 0}function q_(e){return Kf(e)?Mu().requestSchemas[e]:void 0}function M_(e){return Gf(e)?Mu().notificationSchemas[e]:void 0}var nT=Object.keys(Jf),oT=Object.keys(Bf);function Ou(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ka(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Pf={ok:!1,reason:"not-in-era"};function kf(e){return Ou(e)&&Ou(e.outputSchema)&&Hf(e.outputSchema)}var Uu={era:"2025-11-25",hasRequestMethod:Kf,hasNotificationMethod:Gf,validateRequest:(e,t)=>Ka(q_(e),t),validateResult:(e,t)=>Ka(A_(e),t),validateNotification:(e,t)=>Ka(M_(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Pf,validateInputResponse:()=>Pf,samplingResultVariant:((e,t)=>{let r=Ff();return Ka(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let r=Vf(e),n=r.structuredContent;if(n===void 0)return r;let o=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&Hf(t);return!o&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Ou(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>kf(n))?t:{...t,tools:r.map(n=>kf(n)?{...n,outputSchema:N_(n.outputSchema)}:n)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function U_(){let e=Ar(()=>W([u(),Z(),G(),qt(),B(u(),e),O(e)])),t=B(u(),e),r=W([u(),Z().int()]),n=u(),o=W([u(),Z().int()]),i=se(["user","assistant"]),a=se(["debug","info","notice","warning","error","critical","alert","emergency"]),c=u().refine(xe=>{try{return atob(xe),!0}catch{return!1}},{message:"Invalid Base64 string"}),s=E({ttl:Z().optional()}),l=E({taskId:u()}),m=ne({progressToken:r.optional(),"io.modelcontextprotocol/related-task":l.optional()}),h=E({_meta:m.optional()}),z=h.extend({task:s.optional()}),R=E({_meta:m.optional()}),v=E({method:u(),params:R.loose().optional()}),b=E({src:u(),mimeType:u().optional(),sizes:O(u()).optional(),theme:se(["light","dark"]).optional()}),g=E({icons:O(b).optional()}),d=E({name:u(),title:u().optional()}),_=d.extend({...d.shape,...g.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),p=gt(E({applyDefaults:G().optional()}),t),S=ar(xe=>xe&&typeof xe=="object"&&!Array.isArray(xe)&&Object.keys(xe).length===0?{form:{}}:xe,gt(E({form:p.optional(),url:t.optional()}),t.optional())),w=ne({list:t.optional(),cancel:t.optional(),requests:ne({sampling:ne({createMessage:t.optional()}).optional(),elicitation:ne({create:t.optional()}).optional()}).optional()}),y=ne({list:t.optional(),cancel:t.optional(),requests:ne({tools:ne({call:t.optional()}).optional()}).optional()}),f=E({experimental:B(u(),t).optional(),sampling:E({context:t.optional(),tools:t.optional()}).optional(),elicitation:S.optional(),roots:E({listChanged:G().optional()}).optional(),tasks:w.optional(),extensions:B(u(),t).optional()}),T=E({experimental:B(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:E({listChanged:G().optional()}).optional(),resources:E({subscribe:G().optional(),listChanged:G().optional()}).optional(),tools:E({listChanged:G().optional()}).optional(),tasks:y.optional(),extensions:B(u(),t).optional()}),A=E({progress:Z(),total:Q(Z()),message:Q(u())}),F=E({...R.shape,...A.shape,progressToken:r}),M=v.extend({method:j("notifications/progress"),params:F}),D=R.extend({level:a,logger:u().optional(),data:ee()}),Y=v.extend({method:j("notifications/message"),params:D}),K=E({uri:u(),mimeType:Q(u()),_meta:B(u(),ee()).optional()}),fe=K.extend({text:u()}),Te=K.extend({blob:c}),ze=E({audience:O(i).optional(),priority:Z().min(0).max(1).optional(),lastModified:lt.datetime({offset:!0}).optional()}),Ce=E({...d.shape,...g.shape,uri:u(),description:Q(u()),mimeType:Q(u()),size:Q(Z()),annotations:ze.optional(),_meta:Q(ne({}))}),ve=E({...d.shape,...g.shape,uriTemplate:u(),description:Q(u()),mimeType:Q(u()),annotations:ze.optional(),_meta:Q(ne({}))}),k=v.extend({method:j("notifications/resources/list_changed"),params:R.optional()}),x=R.extend({uri:u()}),V=v.extend({method:j("notifications/resources/updated"),params:x}),$=E({name:u(),description:Q(u()),required:Q(G())}),P=E({...d.shape,...g.shape,description:Q(u()),arguments:Q(O($)),_meta:Q(ne({}))}),N=v.extend({method:j("notifications/prompts/list_changed"),params:R.optional()}),H=E({type:j("text"),text:u(),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),te=E({type:j("image"),data:c,mimeType:u(),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),pe=E({type:j("audio"),data:c,mimeType:u(),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),ae=E({type:j("tool_use"),name:u(),id:u(),input:B(u(),ee()),_meta:B(u(),ee()).optional()}),Re=E({type:j("resource"),resource:W([fe,Te]),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),Ge=Ce.extend({type:j("resource_link")}),I=W([H,te,pe,Ge,Re]),C=E({role:i,content:I}),U=E({title:u().optional(),readOnlyHint:G().optional(),destructiveHint:G().optional(),idempotentHint:G().optional(),openWorldHint:G().optional()}),oe=v.extend({method:j("notifications/tools/list_changed"),params:R.optional()}),ie=E({name:u().optional()}),me=E({hints:O(ie).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),Ne=E({mode:se(["auto","required","none"]).optional()}),qe=E({type:j("boolean"),title:u().optional(),description:u().optional(),default:G().optional()}),Fe=E({type:j("string"),title:u().optional(),description:u().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:se(["email","uri","date","date-time"]).optional(),default:u().optional()}),Ae=E({type:se(["number","integer"]),title:u().optional(),description:u().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),Ie=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),default:u().optional()}),nt=E({type:j("string"),title:u().optional(),description:u().optional(),oneOf:O(E({const:u(),title:u()})),default:u().optional()}),Ue=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),enumNames:O(u()).optional(),default:u().optional()}),_t=W([Ie,nt]),at=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({type:j("string"),enum:O(u())}),default:O(u()).optional()}),St=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({anyOf:O(E({const:u(),title:u()}))}),default:O(u()).optional()}),Et=W([at,St]),It=W([Ue,_t,Et]),Bt=W([It,qe,Fe,Ae]),Kt=z.extend({mode:j("form").optional(),message:u(),requestedSchema:E({type:j("object"),properties:B(u(),Bt),required:O(u()).optional()}).catchall(ee())}),Gt=E({type:j("ref/resource"),uri:u()}),Wt=E({type:j("ref/prompt"),name:u()}),en=E({uri:u().startsWith("file://"),name:u().optional(),_meta:B(u(),ee()).optional()}),Pt=f.shape,tn=E({experimental:Pt.experimental,sampling:Pt.sampling,elicitation:Pt.elicitation,roots:Pt.roots,extensions:Pt.extensions}),ot=T.shape,hr=E({experimental:ot.experimental,logging:ot.logging,completions:ot.completions,prompts:ot.prompts,resources:ot.resources,tools:ot.tools,extensions:ot.extensions}),gr=ne({progressToken:r.optional(),[ur]:u(),[qr]:_.optional(),[wt]:tn,[Ut]:a.optional()}),Yt=E({...d.shape,...g.shape,description:u().optional(),inputSchema:ne({$schema:u().optional(),type:j("object")}),outputSchema:ne({$schema:u().optional()}).optional(),annotations:U.optional(),_meta:B(u(),ee()).optional()}),rn=E({type:j("tool_result"),toolUseId:u(),content:O(I),structuredContent:ee().optional(),isError:G().optional(),_meta:B(u(),ee()).optional()}),vr=W([H,te,pe,ae,rn]),Xt=E({role:i,content:W([vr,O(vr)]),_meta:B(u(),ee()).optional()}),_r=u(),Sr=ne({[Rt]:_.optional().catch(void 0)}),yr=Sr.optional();function He(xe){return ne({_meta:yr,resultType:_r.default("complete"),...xe})}let nn=He({}),To=He({nextCursor:n.optional()}),br=He({content:O(I),structuredContent:ee().optional(),isError:G().optional()}),on=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),tools:O(Yt),nextCursor:n.optional()}),an=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),prompts:O(P),nextCursor:n.optional()}),sn=He({description:u().optional(),messages:O(C)}),cn=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resources:O(Ce),nextCursor:n.optional()}),un=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resourceTemplates:O(ve),nextCursor:n.optional()}),ln=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),contents:O(W([fe,Te]))}),dn=He({completion:E({values:O(u()).max(100),total:Z().int().optional(),hasMore:G().optional()}).loose()}),Eo=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"])}),mn=He({ttlMs:Z().int().min(0).catch(0),cacheScope:se(["public","private"]).catch("private"),supportedVersions:O(u()),capabilities:hr,instructions:u().optional()}),kt=E({messages:O(Xt),modelPreferences:me.optional(),systemPrompt:u().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:O(u()).optional(),metadata:t.optional(),tools:O(Yt).optional(),toolChoice:Ne.optional()}),pn=E({method:j("sampling/createMessage"),params:kt}),fn=E({method:j("roots/list"),params:E({_meta:B(u(),ee()).optional()}).optional()}),hn=E({...Xt.shape,model:u(),stopReason:u().optional()}),gn=E({roots:O(en)}),vn=E({action:se(["accept","decline","cancel"]),content:B(u(),W([u(),Z(),G(),O(u())])).optional()}),_n=E({mode:j("url"),message:u(),url:u().url()}),Sn=W([Kt,_n]),yn=E({method:j("elicitation/create"),params:Sn}),bn=W([pn,fn,yn]),$n=W([hn,gn,vn]),zn=B(u(),bn),Rn=B(u(),$n),Qt=He({inputRequests:zn.optional(),requestState:u().optional()}),er={inputResponses:Rn.optional(),requestState:u().optional()},Io=E({_meta:gr,...er}),Po=ne({progressToken:r.optional()});function et(xe,rr){return E({method:j(xe),params:E({_meta:gr,...rr})})}function tt(xe,rr){return E({method:j(xe),params:E({_meta:Po.optional(),...rr}).optional()})}let wn={name:u(),arguments:B(u(),ee()).optional(),...er},st={cursor:n.optional()},ko=et("tools/call",wn),Oo=et("tools/list",st),jo=et("prompts/list",st),No=et("prompts/get",{name:u(),arguments:B(u(),u()).optional(),...er}),xo=et("resources/list",st),Co=et("resources/templates/list",st),Ao=et("resources/read",{uri:u(),...er}),Tn={ref:W([Wt,Gt]),argument:E({name:u(),value:u()}),context:E({arguments:B(u(),u()).optional()}).optional()},qo=et("completion/complete",Tn),Mo=et("server/discover",{}),$r=E({toolsListChanged:G().optional(),promptsListChanged:G().optional(),resourcesListChanged:G().optional(),resourceSubscriptions:O(u()).optional()}),En={notifications:$r},Uo=et("subscriptions/listen",En),Lo=Sr.extend({"io.modelcontextprotocol/subscriptionId":o}),Do=ne({_meta:Lo,resultType:_r.default("complete")}),Ot={"tools/call":tt("tools/call",wn),"tools/list":tt("tools/list",st),"prompts/get":tt("prompts/get",{name:u(),arguments:B(u(),u()).optional()}),"prompts/list":tt("prompts/list",st),"resources/list":tt("resources/list",st),"resources/templates/list":tt("resources/templates/list",st),"resources/read":tt("resources/read",{uri:u()}),"completion/complete":tt("completion/complete",Tn),"server/discover":tt("server/discover",{}),"subscriptions/listen":tt("subscriptions/listen",En)};function Xe(xe){return ne({_meta:yr,...xe})}let Vo={"tools/call":Xe({content:O(I),structuredContent:ee().optional(),isError:G().optional()}),"tools/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),tools:O(Yt),nextCursor:n.optional()}),"prompts/get":Xe({description:u().optional(),messages:O(C)}),"prompts/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),prompts:O(P),nextCursor:n.optional()}),"resources/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resources:O(Ce),nextCursor:n.optional()}),"resources/templates/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resourceTemplates:O(ve),nextCursor:n.optional()}),"resources/read":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),contents:O(W([fe,Te]))}),"completion/complete":Xe({completion:E({values:O(u()).max(100),total:Z().int().optional(),hasMore:G().optional()}).loose()}),"server/discover":Xe({ttlMs:Z().int().min(0).catch(0),cacheScope:se(["public","private"]).catch("private"),supportedVersions:O(u()),capabilities:hr,instructions:u().optional()}),"subscriptions/listen":Xe({})},tr=ne({"io.modelcontextprotocol/subscriptionId":o.optional()}),zr=E({method:j("notifications/subscriptions/acknowledged"),params:E({_meta:tr.optional(),notifications:$r})}),Rr=E({_meta:tr.optional(),requestId:o,reason:u().optional()}),wr=E({method:j("notifications/cancelled"),params:Rr}),bs={"notifications/cancelled":wr,"notifications/progress":M,"notifications/message":Y,"notifications/resources/updated":V,"notifications/resources/list_changed":k,"notifications/tools/list_changed":oe,"notifications/prompts/list_changed":N,"notifications/subscriptions/acknowledged":zr},Qe=xe=>E({jsonrpc:j("2.0"),id:W([u(),Z().int()]),result:xe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:o,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:s,RelatedTaskMetadataSchema:l,RequestMetaSchema:m,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:z,NotificationsParamsSchema:R,NotificationSchema:v,IconSchema:b,IconsSchema:g,BaseMetadataSchema:d,ImplementationSchema:_,ClientTasksCapabilitySchema:w,ServerTasksCapabilitySchema:y,ClientCapabilitiesSchema:f,ServerCapabilitiesSchema:T,ProgressSchema:A,ProgressNotificationParamsSchema:F,ProgressNotificationSchema:M,LoggingMessageNotificationParamsSchema:D,LoggingMessageNotificationSchema:Y,ResourceContentsSchema:K,TextResourceContentsSchema:fe,BlobResourceContentsSchema:Te,AnnotationsSchema:ze,ResourceSchema:Ce,ResourceTemplateSchema:ve,ResourceListChangedNotificationSchema:k,ResourceUpdatedNotificationParamsSchema:x,ResourceUpdatedNotificationSchema:V,PromptArgumentSchema:$,PromptSchema:P,PromptListChangedNotificationSchema:N,TextContentSchema:H,ImageContentSchema:te,AudioContentSchema:pe,ToolUseContentSchema:ae,EmbeddedResourceSchema:Re,ResourceLinkSchema:Ge,ContentBlockSchema:I,PromptMessageSchema:C,ToolAnnotationsSchema:U,ToolListChangedNotificationSchema:oe,ModelHintSchema:ie,ModelPreferencesSchema:me,ToolChoiceSchema:Ne,BooleanSchemaSchema:qe,StringSchemaSchema:Fe,NumberSchemaSchema:Ae,UntitledSingleSelectEnumSchemaSchema:Ie,TitledSingleSelectEnumSchemaSchema:nt,LegacyTitledEnumSchemaSchema:Ue,SingleSelectEnumSchemaSchema:_t,UntitledMultiSelectEnumSchemaSchema:at,TitledMultiSelectEnumSchemaSchema:St,MultiSelectEnumSchemaSchema:Et,EnumSchemaSchema:It,PrimitiveSchemaDefinitionSchema:Bt,ElicitRequestFormParamsSchema:Kt,ResourceTemplateReferenceSchema:Gt,PromptReferenceSchema:Wt,RootSchema:en,ClientCapabilities2026Schema:tn,ServerCapabilities2026Schema:hr,RequestMetaEnvelopeSchema:gr,ToolSchema:Yt,ToolResultContentSchema:rn,SamplingMessageContentBlockSchema:vr,SamplingMessageSchema:Xt,ResultTypeSchema:_r,ResultMetaSchema:Sr,ResultSchema:nn,PaginatedResultSchema:To,CallToolResultSchema:br,ListToolsResultSchema:on,ListPromptsResultSchema:an,GetPromptResultSchema:sn,ListResourcesResultSchema:cn,ListResourceTemplatesResultSchema:un,ReadResourceResultSchema:ln,CompleteResultSchema:dn,CacheableResultSchema:Eo,DiscoverResultSchema:mn,CreateMessageRequestParamsSchema:kt,CreateMessageRequestSchema:pn,ListRootsRequestSchema:fn,CreateMessageResultSchema:hn,ListRootsResultSchema:gn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:_n,ElicitRequestParamsSchema:Sn,ElicitRequestSchema:yn,InputRequestSchema:bn,InputResponseSchema:$n,InputRequestsSchema:zn,InputResponsesSchema:Rn,InputRequiredResultSchema:Qt,InputResponseRequestParamsSchema:Io,CallToolRequestSchema:ko,ListToolsRequestSchema:Oo,ListPromptsRequestSchema:jo,GetPromptRequestSchema:No,ListResourcesRequestSchema:xo,ListResourceTemplatesRequestSchema:Co,ReadResourceRequestSchema:Ao,CompleteRequestSchema:qo,DiscoverRequestSchema:Mo,SubscriptionFilterSchema:$r,SubscriptionsListenRequestSchema:Uo,SubscriptionsListenResultMetaSchema:Lo,SubscriptionsListenResultSchema:Do,dispatchRequestSchemas:Ot,dispatchResultSchemas:Vo,NotificationMetaSchema:tr,SubscriptionsAcknowledgedNotificationSchema:zr,CancelledNotificationParamsSchema:Rr,CancelledNotificationSchema:wr,notificationSchemas2026:bs,JSONRPCResultResponseSchema:Qe(nn),CallToolResultResponseSchema:Qe(W([br,Qt])),ListToolsResultResponseSchema:Qe(on),ListPromptsResultResponseSchema:Qe(an),GetPromptResultResponseSchema:Qe(W([sn,Qt])),ListResourcesResultResponseSchema:Qe(cn),ListResourceTemplatesResultResponseSchema:Qe(un),ReadResourceResultResponseSchema:Qe(W([ln,Qt])),CompleteResultResponseSchema:Qe(dn),DiscoverResultResponseSchema:Qe(mn)}}var L_;function pr(){return L_??=U_()}var D_=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function V_(e){return D_.includes(e)}var Gr=Symbol("modelcontextprotocol.resultCacheHintFallback");function Wf(e,t){if(t===void 0)return e;let r=e[Gr];if(r===void 0)return{...e,[Gr]:t};let n={},o=r.ttlMs??t.ttlMs;o!==void 0&&(n.ttlMs=o);let i=r.cacheScope??t.cacheScope;return i!==void 0&&(n.cacheScope=i),{...e,[Gr]:n}}function Z_(e){return e[Gr]}function Lu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Du(e){return e==="public"||e==="private"}function Yf(e,t){if(e.ttlMs!==void 0&&!Lu(e.ttlMs))throw new RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!Du(e.cacheScope))throw new RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}var X=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),ge=class Xf extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Wr(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Wr(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",Cu(this,new.target)}static fromError(t,r,n){if(t===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Qf(o.elicitations,r)}if(t===X.UnsupportedProtocolVersion&&n){let o=n;if(Array.isArray(o.supported)&&typeof o.requested=="string")return new Zu({supported:o.supported,requested:o.requested},r)}if(t===X.InvalidParams||t===X.ResourceNotFound){let o=n;if(typeof o?.uri=="string"&&(t===X.ResourceNotFound||Object.keys(o).length===1))return new Vu(o.uri,r)}if(t===X.MissingRequiredClientCapability&&n){let o=n;if(o.requiredCapabilities!==null&&typeof o.requiredCapabilities=="object"&&!Array.isArray(o.requiredCapabilities))return new ts({requiredCapabilities:o.requiredCapabilities},r)}return new Xf(t,r,n)}},Vu=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(X.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Qf=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Zu=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(X.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},ts=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(X.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},F_=0,H_="private",J_=["tools/call","prompts/get","resources/read"];function B_(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||J_.includes(e))return t;throw new ge(X.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function K_(e,t){let r=Z_(t);if(t.resultType!=="complete"||!V_(e))return r===void 0?t:Q_(t);let n=t,o=Lu(n.ttlMs)?n.ttlMs:Y_(r),i=Du(n.cacheScope)?n.cacheScope:X_(r),a={...n,ttlMs:o,cacheScope:i};return delete a[Gr],a}function G_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W_(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Rt]:t}}:!G_(r)||r[Rt]!==void 0?e:{...e,_meta:{...r,[Rt]:t}}}function Y_(e){return e!==void 0&&Lu(e.ttlMs)?e.ttlMs:F_}function X_(e){return e!==void 0&&Du(e.cacheScope)?e.cacheScope:H_}function Q_(e){let t={...e};return delete t[Gr],t}var eS=["elicitation/create","sampling/createMessage","roots/list"],Ga;function eh(){if(Ga)return Ga;let e=pr();return Ga={request:{"elicitation/create":E({method:j("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":E({method:j("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":E({method:j("roots/list"),params:ne({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Ga}function th(e){return eS.includes(e)}function Tu(e){return th(e)?eh().request[e]:void 0}function tS(e){return th(e)?eh().response[e]:void 0}var Fu={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},rh={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function nh(e){return Object.prototype.hasOwnProperty.call(Fu,e)}function oh(e){return Object.prototype.hasOwnProperty.call(rh,e)}function rS(e){return Object.prototype.hasOwnProperty.call(Fu,e)}function nS(e){return nh(e)?pr().dispatchRequestSchemas[e]:void 0}function oS(e){return rS(e)?pr().dispatchResultSchemas[e]:void 0}function iS(e){return oh(e)?pr().notificationSchemas2026[e]:void 0}var iT=Object.keys(Fu),aT=Object.keys(rh);function So(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var aS={ok:!1,reason:"not-in-era"},sS=[ur,wt];function cS(e,t){let r=t,n=!1,o=()=>(n||(r={...r},n=!0),r),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>So(c)&&"execution"in c)&&(o().tools=i.map(c=>{if(!So(c)||!("execution"in c))return c;let s={...c};return delete s.execution,s}));let a=t.capabilities;if(So(a)&&"tasks"in a){let c={...a};delete c.tasks,o().capabilities=c}return r}var Hu={era:"2026-07-28",hasRequestMethod:nh,hasNotificationMethod:oh,hasInputRequestMethod:e=>Tu(e)!==void 0,validateRequest:(e,t)=>vo(nS(e),t),validateResult:(e,t)=>vo(oS(e),t),validateNotification:(e,t)=>vo(iS(e),t),validateInputRequest:(e,t)=>vo(Tu(e),t),validateInputResponse:(e,t)=>vo(tS(e),t),samplingResultVariant:()=>aS,outboundEnvelope(e){return{[ur]:e.protocolVersion,[qr]:e.clientInfo,[wt]:e.clientCapabilities,...e.logLevel!==void 0&&{[Ut]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of sS)n in e||t.push({key:n,problem:"missing"});let r=pr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let o=n.path.map(String),i=o.length>0?o.join("."):"_meta";o.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:e=>Vf(e),inputRequestSchema:Tu,decodeResult(e,t){if(!So(t))return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=So(a)?a:{},s=t.requestState;return Object.keys(c).length===0&&typeof s!="string"?{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof s=="string"&&{requestState:s}}}if(r!=="complete")return{kind:"invalid",error:new le(he.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=uS(),o=Object.hasOwn(n,e)?n[e]:void 0;if(o!==void 0){let a=o.safeParse(t);if(!a.success)return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return W_(K_(e,B_(e,cS(e,t))),r)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=pr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Wa;function uS(){if(Wa)return Wa;let e=pr();return Wa={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Wa}var Ju="2026-07-28";function Yr(e){return e!==void 0&&$o(e)?Hu:Uu}function Of(e){return e.revision!==void 0?Yr(e.revision).era:e.era==="modern"?Hu.era:Uu.era}function Eu(e){return ih.some(t=>t.hasRequestMethod(e))}function Iu(e){return ih.some(t=>t.hasNotificationMethod(e))}var ih=[Uu,Hu];var lS=Rl({AnnotationsSchema:()=>Tt,AudioContentSchema:()=>Fr,BaseMetadataSchema:()=>zt,BaseRequestParamsSchema:()=>De,BlobResourceContentsSchema:()=>oo,BooleanSchemaSchema:()=>uo,CallToolRequestParamsSchema:()=>aa,CallToolRequestSchema:()=>sa,CallToolResultSchema:()=>co,CancelTaskRequestSchema:()=>lu,CancelTaskResultSchema:()=>du,CancelledNotificationParamsSchema:()=>ui,CancelledNotificationSchema:()=>Xn,ClientCapabilitiesSchema:()=>pi,ClientNotificationSchema:()=>pu,ClientRequestSchema:()=>mu,ClientResultSchema:()=>fu,ClientTasksCapabilitySchema:()=>di,CompatibilityCallToolResultSchema:()=>Qc,CompleteRequestParamsSchema:()=>xa,CompleteRequestSchema:()=>Ca,CompleteResultSchema:()=>Aa,ContentBlockSchema:()=>Hr,CreateMessageRequestParamsSchema:()=>Sa,CreateMessageRequestSchema:()=>ya,CreateMessageResultSchema:()=>ba,CreateMessageResultWithToolsSchema:()=>$a,CreateTaskResultSchema:()=>ru,CursorSchema:()=>Hn,DiscoverRequestSchema:()=>_i,DiscoverResultSchema:()=>Si,ElicitRequestFormParamsSchema:()=>Kr,ElicitRequestParamsSchema:()=>Ea,ElicitRequestSchema:()=>Ia,ElicitRequestURLParamsSchema:()=>Ta,ElicitResultSchema:()=>Oa,ElicitationCompleteNotificationParamsSchema:()=>Pa,ElicitationCompleteNotificationSchema:()=>ka,EmbeddedResourceSchema:()=>Yi,EmptyResultSchema:()=>Yn,EnumSchemaSchema:()=>wa,GetPromptRequestParamsSchema:()=>Ki,GetPromptRequestSchema:()=>Gi,GetPromptResultSchema:()=>ea,GetTaskPayloadRequestSchema:()=>au,GetTaskPayloadResultSchema:()=>su,GetTaskRequestSchema:()=>ou,GetTaskResultSchema:()=>iu,IconSchema:()=>li,IconsSchema:()=>Dt,ImageContentSchema:()=>Zr,ImplementationSchema:()=>Lr,InitializeRequestParamsSchema:()=>fi,InitializeRequestSchema:()=>hi,InitializeResultSchema:()=>gi,InitializedNotificationSchema:()=>vi,JSONArraySchema:()=>Wc,JSONObjectSchema:()=>ke,JSONRPCErrorResponseSchema:()=>Ur,JSONRPCMessageSchema:()=>Wn,JSONRPCNotificationSchema:()=>Gn,JSONRPCRequestSchema:()=>Kn,JSONRPCResponseSchema:()=>Yc,JSONRPCResultResponseSchema:()=>Mr,JSONValueSchema:()=>Mt,LegacyTitledEnumSchemaSchema:()=>po,ListChangedOptionsBaseSchema:()=>eu,ListPromptsRequestSchema:()=>Ji,ListPromptsResultSchema:()=>Bi,ListResourceTemplatesRequestSchema:()=>Ti,ListResourceTemplatesResultSchema:()=>Ei,ListResourcesRequestSchema:()=>Ri,ListResourcesResultSchema:()=>wi,ListRootsRequestSchema:()=>Ma,ListRootsResultSchema:()=>Ua,ListTasksRequestSchema:()=>cu,ListTasksResultSchema:()=>uu,ListToolsRequestSchema:()=>oa,ListToolsResultSchema:()=>ia,LoggingLevelSchema:()=>Ht,LoggingMessageNotificationParamsSchema:()=>da,LoggingMessageNotificationSchema:()=>ma,ModelHintSchema:()=>pa,ModelPreferencesSchema:()=>fa,MultiSelectEnumSchemaSchema:()=>Ra,NotificationSchema:()=>Ke,NotificationsParamsSchema:()=>Be,NumberSchemaSchema:()=>Br,PaginatedRequestParamsSchema:()=>$i,PaginatedRequestSchema:()=>Vt,PaginatedResultSchema:()=>Zt,PingRequestSchema:()=>eo,PrimitiveSchemaDefinitionSchema:()=>go,ProgressNotificationParamsSchema:()=>bi,ProgressNotificationSchema:()=>to,ProgressSchema:()=>yi,ProgressTokenSchema:()=>Fn,PromptArgumentSchema:()=>Fi,PromptListChangedNotificationSchema:()=>ta,PromptMessageSchema:()=>Qi,PromptReferenceSchema:()=>Na,PromptSchema:()=>Hi,ReadResourceRequestParamsSchema:()=>Ii,ReadResourceRequestSchema:()=>Pi,ReadResourceResultSchema:()=>ki,RelatedTaskMetadataSchema:()=>ci,RequestIdSchema:()=>Lt,RequestMetaSchema:()=>Jn,RequestSchema:()=>Oe,ResourceContentsSchema:()=>ro,ResourceLinkSchema:()=>Xi,ResourceListChangedNotificationSchema:()=>Oi,ResourceRequestParamsSchema:()=>Dr,ResourceSchema:()=>io,ResourceTemplateReferenceSchema:()=>ja,ResourceTemplateSchema:()=>zi,ResourceUpdatedNotificationParamsSchema:()=>Vi,ResourceUpdatedNotificationSchema:()=>Zi,ResultMetaObjectSchema:()=>Bn,ResultSchema:()=>je,RoleSchema:()=>Ft,RootSchema:()=>qa,RootsListChangedNotificationSchema:()=>La,SamplingContentSchema:()=>va,SamplingMessageContentBlockSchema:()=>sr,SamplingMessageSchema:()=>_a,ServerCapabilitiesSchema:()=>Qn,ServerNotificationSchema:()=>gu,ServerRequestSchema:()=>hu,ServerResultSchema:()=>vu,ServerTasksCapabilitySchema:()=>mi,SetLevelRequestParamsSchema:()=>ua,SetLevelRequestSchema:()=>la,SingleSelectEnumSchemaSchema:()=>za,StringSchemaSchema:()=>Jr,SubscribeRequestParamsSchema:()=>ji,SubscribeRequestSchema:()=>Ni,SubscriptionFilterSchema:()=>ao,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Mi,SubscriptionsAcknowledgedNotificationSchema:()=>Ui,SubscriptionsListenRequestParamsSchema:()=>Ai,SubscriptionsListenRequestSchema:()=>qi,SubscriptionsListenResultMetaSchema:()=>Li,SubscriptionsListenResultSchema:()=>Di,TaskAugmentedRequestParamsSchema:()=>dr,TaskCreationParamsSchema:()=>tu,TaskMetadataSchema:()=>si,TaskSchema:()=>Jt,TaskStatusNotificationParamsSchema:()=>Va,TaskStatusNotificationSchema:()=>nu,TaskStatusSchema:()=>Da,TextContentSchema:()=>Vr,TextResourceContentsSchema:()=>no,TitledMultiSelectEnumSchemaSchema:()=>ho,TitledSingleSelectEnumSchemaSchema:()=>mo,ToolAnnotationsSchema:()=>ra,ToolChoiceSchema:()=>ha,ToolExecutionSchema:()=>na,ToolListChangedNotificationSchema:()=>ca,ToolResultContentSchema:()=>ga,ToolSchema:()=>so,ToolUseContentSchema:()=>Wi,UnsubscribeRequestParamsSchema:()=>xi,UnsubscribeRequestSchema:()=>Ci,UntitledMultiSelectEnumSchemaSchema:()=>fo,UntitledSingleSelectEnumSchemaSchema:()=>lo});var Bu=e=>Kn.safeParse(e).success,Ku=e=>Gn.safeParse(e).success,Qa=e=>Mr.safeParse(e).success,Gu=e=>Ur.safeParse(e).success;var fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var Ya=-32020,sT=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[X.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Ya,X.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[X.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[X.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[X.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Ya],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[X.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Ya],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],dS={[X.ParseError]:400,[X.InvalidRequest]:400,[X.MethodNotFound]:404,[X.UnsupportedProtocolVersion]:400,[X.MissingRequiredClientCapability]:400,[Ya]:400};function rs(e,t){return ti(e,t)}function _o(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function ju(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}var jf=!1,Nu="draft-2020-12";function ah(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Nu});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");jf||(jf=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=Dn(e,{target:Nu,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:sh(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}function sh(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||sh(n)))}return!1}function mS(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Xa(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>mS(n)).join(", ")}:{success:!0,data:r.value}}function pS(e){let t=Dn(e,{target:Nu,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}var fS=/\\\.\\d\{(\d+)\}/;function hS(e){let t=fS.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(o=>r.map(i=>lt.datetime({local:n,offset:o,precision:i}))))}function gS(e,t){let r;switch(e){case"email":r=[Hc()];break;case"uri":r=[Vn()];break;case"date":r=[lt.date()];break;case"date-time":r=hS(t);break}return new Set(r.map(n=>pS(n)).filter(n=>n!==void 0))}function vS(e,t,r){return r!=="zod"?!0:gS(e,t).has(t)}function bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _S(e){try{return ah(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ge(X.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var SS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Wu(e){return SS.has(e)||e.startsWith("x-")}var yS=new Set(["$schema",...Object.keys(Kr.shape.requestedSchema.shape)]),Nf={string:_o([Jr,lo,mo,po]),number:_o([Br]),integer:_o([Br]),boolean:_o([uo]),array:_o([fo,ho])},bS=new Set(Jr.shape.format.unwrap().options);function $S(e,t,r,n){if(!bo(e))return e;let o=typeof e.type=="string"&&Object.hasOwn(Nf,e.type)?Nf[e.type]:void 0;if(o===void 0)return e;let i={};for(let[a,c]of Object.entries(e))o.has(a)||Wu(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?bS.has(e.format)?(typeof c!="string"||!vS(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}function zS(e,t){let r={},n=[];for(let[o,i]of Object.entries(e))o==="properties"&&bo(i)?r[o]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,$S(c,`properties.${a}`,t,n)])):yS.has(o)?r[o]=i:Wu(o)||n.push(o);if(n.length>0)throw new ge(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}function RS(e,t){if(!bo(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!rs(go,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}function xu(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,o)=>xu(n,t[o],`${r}[${o}]`)):!bo(e)||!bo(t)?[]:Object.entries(e).flatMap(([n,o])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?xu(o,t[n],i):Wu(n)?[]:[i]})}function wS(e){if(!ju(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=zS(_S(e.requestedSchema),t),n=rs(Kr.shape.requestedSchema,r);if(!n.success)throw new ge(X.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${RS(r,n.error.message)}`);let o=xu(r,n.data);if(o.length>0)throw new ge(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new ge(X.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}function TS(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var ES=Object.assign(TS,{elicit(e){try{return{method:"elicitation/create",params:wS(e)}}catch(t){throw t instanceof ge?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var ch=250;function uh(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function lh(e,t){return new Promise((r,n)=>{if(t?.aborted){n(t.reason instanceof le?t.reason:new le(he.RequestTimeout,String(t.reason)));return}let o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(o),n(t?.reason instanceof le?t.reason:new le(he.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function dh(e){let t=new AbortController,r=()=>t.abort(e?.reason);return e?.addEventListener("abort",r,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:n=>t.abort(n),dispose:()=>e?.removeEventListener("abort",r)}}var IS=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],PS={IdJagTokenExchangeResponseSchema:bu,OAuthClientInformationFullSchema:zu,OAuthClientInformationSchema:Ja,OAuthClientMetadataSchema:Ha,OAuthClientRegistrationErrorSchema:Ru,OAuthErrorResponseSchema:$u,OAuthMetadataSchema:Za,OAuthProtectedResourceMetadataSchema:_u,OAuthTokenRevocationRequestSchema:wu,OAuthTokensSchema:yu,OpenIdProviderDiscoveryMetadataSchema:Su,OpenIdProviderMetadataSchema:Fa},mh={},ph={};function fh(e,t){let r=e.slice(0,-6);mh[r]=t,ph[r]=n=>t.safeParse(n).success}for(let e of IS)fh(e,lS[e]);for(let[e,t]of Object.entries(PS))fh(e,t);var kS=Object.freeze(mh),OS=Object.freeze(ph);function jS(e){switch(e){case"initialize":case"notifications/initialized":return Yr(void 0);case"server/discover":return Yr(Ju);default:return}}var hh=6e4,NS=[ur,qr,wt,Ut],xS=["inputResponses","requestState"];function xf(e,t){let r=e.params;if(!yo(r))return{message:e,lifted:{}};let n=r._meta,o=yo(n)?NS.filter(s=>s in n):[],i=t==="request"?xS.filter(s=>s in r):[];if(o.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(o.length>0&&yo(n)){let s={},l={...n};for(let m of o)s[m]=n[m],delete l[m];a.envelope=s,Object.keys(l).length>0?c._meta=l:delete c._meta}for(let s of i)s==="inputResponses"&&(a.inputResponses=c[s]),s==="requestState"&&(a.requestState=c[s]),delete c[s];return{message:{...e,params:c},lifted:a}}function Cf(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let o=e.validateResult(t,n);return o.ok?{value:o.value}:{issues:[{message:o.reason==="invalid"?o.message:`not-in-era: ${t}`}]}}}}}function zo(e){return()=>e}var CS=zo(void 0);function Yu(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:zo(t)}}}var AS;var Xu=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{AS=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ii,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new le(he.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new le(he.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),Qa(o)||Gu(o)?this._onresponse(o):Bu(o)?this._onrequest(o,i):Ku(o)?this._onnotification(o,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new le(he.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=xf(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Of(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(Iu(r.method)&&!n.hasNotificationMethod(r.method))return;let o=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;o===void 0&&i===void 0||Promise.resolve().then(()=>o===void 0?i(r):o(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=xf(e,"request"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=(b,g,d)=>{let _={jsonrpc:"2.0",id:r.id,error:{code:b,message:g,...d!==void 0&&{data:d}}};i?.send(_).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)))};if(t?.classification!==void 0){let b=Of(t.classification);if(b!==o.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${b} but this instance serves ${o.era}`));let g=t.classification.revision??b;a(X.UnsupportedProtocolVersion,`Unsupported protocol version: ${g}`,{supported:this._supportedProtocolVersions,requested:g});return}}if(Eu(r.method)&&!o.hasRequestMethod(r.method)){a(X.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(X.MethodNotFound,"Method not found");return}let s=o.checkInboundEnvelope(n);if(s!==void 0){a(X.InvalidParams,s);return}let l=(b,g)=>this._notificationViaCodec(this._resolveOutboundCodec(b.method),b,{...g,relatedRequestId:r.id}),m=(b,g,d)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(b.method),b,g,{...d,relatedRequestId:r.id}),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let z=n.inputResponses===void 0?void 0:qS(n.inputResponses),R={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...z!==void 0&&{inputResponses:z.accepted},...z!==void 0&&z.droppedKeys.length>0&&{droppedInputResponseKeys:z.droppedKeys},requestState:n.requestState===void 0?CS:zo(n.requestState),signal:h.signal,send:((b,g,d)=>{let _=this._resolveOutboundCodec(b.method);if(this._assertOutboundRequestInEra(_,b.method),ju(g))return m(b,g,d);let p=Cf(_,b.method);if(p===void 0)throw new TypeError(`'${b.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(b,p,g)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},v=this.buildContext(R,t);Promise.resolve().then(()=>c(r,v)).then(async b=>{if(h.signal.aborted)return;let g;try{g=o.encodeResult(r.method,b,this._outboundServerInfo())}catch(_){this._onerror(new Error(`Failed to encode result for ${r.method}: ${_}`)),a(X.InternalError,"Internal error");return}let d={result:g,jsonrpc:"2.0",id:r.id};await i?.send(d)},async b=>{if(h.signal.aborted)return;let g=Number.isSafeInteger(b.code)?b.code:X.InternalError,d={jsonrpc:"2.0",id:r.id,error:{code:o.encodeErrorCode(g),message:b.message??"Internal error",...b.data!==void 0&&{data:b.data}}};await i?.send(d)}).catch(b=>this._onerror(new Error(`Failed to send response: ${b}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Qa(e)?r(e):r(ge.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(n,e.method),ju(t))return this._requestWithSchemaViaCodec(n,e,t,r);let o=Cf(n,e.method);if(o===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,o,t)}_negotiatedWireCodec(){return Yr(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=jS(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Eu(t)&&!e.hasRequestMethod(t))throw new le(he.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:c}=n??{},s=Date.now(),l,m;return new Promise((h,z)=>{let R=y=>{z(y)};if(!this._transport){R(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(y){R(y);return}if(n?.signal?.aborted){let y=n.signal.reason;throw y instanceof le?y:new le(he.RequestTimeout,String(y))}let v=e.era===Ju&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,b=this._requestMessageId++;m=b;let g={...t,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:b}});let d=this._envelopeOutbound(g),_=!1,p=y=>{_||(this._progressHandlers.delete(b),v===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(y)}}),{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(f=>this._onerror(new Error(`Failed to send cancellation: ${f}`))):v.abort(),z(y instanceof le?y:new le(he.RequestTimeout,String(y))))};this._responseHandlers.set(b,y=>{if(n?.signal?.aborted)return;if(_=!0,y instanceof Error)return z(y);let f;try{f=e.decodeResult(t.method,y.result)}catch(A){return z(A instanceof Error?A:new Error(String(A)))}if(f.kind==="invalid")return z(f.error);if(f.kind==="input_required"){if(n?.allowInputRequired===!0)return h(MS(f));let A={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:s,retry:(F,M)=>this._requestWithSchemaViaCodec(e,F===void 0?{method:t.method}:{method:t.method,params:F},r,M)};return h(this._resolveNonCompleteResult(f,A))}let T=f.result;Xa(r,T).then(A=>{A.success?h(A.data):z(new le(he.InvalidResult,`Invalid result for ${t.method}: ${A.error}`))},z)}),l=()=>p(n?.signal?.reason),n?.signal?.addEventListener("abort",l,{once:!0});let S=n?.timeout??hh,w=()=>p(new le(he.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(b,S,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1),this._transport.send(d,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:v?.signal}).catch(y=>{this._progressHandlers.delete(b),z(y)})}).finally(()=>{l&&n?.signal?.removeEventListener("abort",l),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new le(he.NotConnected,"Not connected");if(Iu(t.method)&&!e.hasNotificationMethod(t.method))throw new le(he.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(o=>this._onerror(o))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Eu(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(o,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,o);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,o)),!c.ok)throw c.reason==="not-in-era"?new ge(X.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))}}else if(r)n=async(o,i)=>{let a=await Xa(t.params,{...o.params});if(!a.success)throw new ge(X.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)};else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}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,r){if(typeof t=="function"){if(!Iu(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,o)=>{let i=o.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new ge(X.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let o=await Xa(t.params,{...n.params});if(!o.success)throw new ge(X.InvalidParams,`Invalid params for notification ${e}: ${o.error}`);await r(o.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function yo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qu(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let a=r[o];r[o]=yo(a)&&yo(i)?{...a,...i}:i}return r}function Af(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qS(e){let t={},r=[];if(!Af(e))return{accepted:t,droppedKeys:r};for(let[n,o]of Object.entries(e)){if(!Af(o)||"method"in o||"result"in o){r.push(n);continue}t[n]=o}return{accepted:t,droppedKeys:r}}function MS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}var US=L((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=o;function o(c){if(!c)throw new TypeError("argument string is required");var s=typeof c=="object"?i(c):c;if(typeof s!="string")throw new TypeError("argument string is required to be a string");var l=s.indexOf(";"),m=l!==-1?s.slice(0,l).trim():s.trim();if(!n.test(m))throw new TypeError("invalid media type");var h=new a(m.toLowerCase());if(l!==-1){var z,R,v;for(t.lastIndex=l;R=t.exec(s);){if(R.index!==l)throw new TypeError("invalid parameter format");l+=R[0].length,z=R[1].toLowerCase(),v=R[2],v.charCodeAt(0)===34&&(v=v.slice(1,-1),v.indexOf("\\")!==-1&&(v=v.replace(r,"$1"))),h.parameters[z]=v}if(l!==s.length)throw new TypeError("invalid parameter format")}return h}function i(c){var s;if(typeof c.getHeader=="function"?s=c.getHeader("content-type"):typeof c.headers=="object"&&(s=c.headers&&c.headers["content-type"]),typeof s!="string")throw new TypeError("content-type header is missing from object");return s}function a(c){this.parameters=Object.create(null),this.type=c}})),cT=Fo(US(),1);var gh=10*1024*1024,el=class{_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??gh}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(` +`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");this._buffer=this._buffer.subarray(e+1);try{return vh(t)}catch(r){if(r instanceof SyntaxError)continue;throw r}}return null}clear(){this._buffer=void 0}};function vh(e){return Wn.parse(JSON.parse(e))}function tl(e){return JSON.stringify(e)+` +`}var qf=1e6,Pu=1e6,Mf=1e4,LS=1e6,ns=class mr{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,n){if(t.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${t.length})`)}template;parts;get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){mr.validateLength(t,qf,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let r=[],n="",o=0,i=0;for(;oMf)throw new Error(`Template contains too many expressions (max ${Mf})`);let c=t.slice(o+1,a),s=this.getOperator(c),l=c.includes("*"),m=this.getNames(c),h=m[0];for(let z of m)mr.validateLength(z,Pu,"Variable name");r.push({name:h,operator:s,names:m,exploded:l}),o=a+1}else n+=t[o],o++;return n&&r.push(n),r}getOperator(t){return["+","#",".","/","?","&"].find(r=>t.startsWith(r))||""}getNames(t){let r=this.getOperator(t);return t.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,r){return mr.validateLength(t,Pu,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){let i=t.names.map(a=>{let c=r[a];return c===void 0?"":`${a}=${Array.isArray(c)?c.map(s=>this.encodeValue(s,t.operator)).join(","):this.encodeValue(c.toString(),t.operator)}`}).filter(a=>a.length>0);return i.length===0?"":(t.operator==="?"?"?":"&")+i.join("&")}if(t.names.length>1){let i=t.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[t.name];if(n===void 0)return"";let o=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,t.operator));switch(t.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(t){let r="",n=!1;for(let o of this.parts){if(typeof o=="string"){r+=o;continue}let i=this.expandPart(o,t);i&&(r+=(o.operator==="?"||o.operator==="&")&&n?i.replace("?","&"):i,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(t){return t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let r=[];for(let i of t.names)mr.validateLength(i,Pu,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let i=0;i{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var r=class extends t{constructor(d){if(super(),!e.IDENTIFIER.test(d))throw new Error("CodeGen: name must be a valid identifier");this.str=d}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=r;var n=class extends t{constructor(d){super(),this._items=typeof d=="string"?[d]:d}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let d=this._items[0];return d===""||d==='""'}get str(){var d;return(d=this._str)!==null&&d!==void 0?d:this._str=this._items.reduce((_,p)=>`${_}${p}`,"")}get names(){var d;return(d=this._names)!==null&&d!==void 0?d:this._names=this._items.reduce((_,p)=>(p instanceof r&&(_[p.str]=(_[p.str]||0)+1),_),{})}};e._Code=n,e.nil=new n("");function o(d,..._){let p=[d[0]],S=0;for(;S<_.length;)c(p,_[S]),p.push(d[++S]);return new n(p)}e._=o;let i=new n("+");function a(d,..._){let p=[R(d[0])],S=0;for(;S<_.length;)p.push(i),c(p,_[S]),p.push(i,R(d[++S]));return s(p),new n(p)}e.str=a;function c(d,_){_ instanceof n?d.push(..._._items):_ instanceof r?d.push(_):d.push(h(_))}e.addCodeArg=c;function s(d){let _=1;for(;_{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=is();var r=class extends Error{constructor(s){super(`CodeGen: "code" for ${s} not defined`),this.value=s.value}},n;(function(s){s[s.Started=0]="Started",s[s.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};var o=class{constructor({prefixes:s,parent:l}={}){this._names={},this._prefixes=s,this._parent=l}toName(s){return s instanceof t.Name?s:this.name(s)}name(s){return new t.Name(this._newName(s))}_newName(s){let l=this._names[s]||this._nameGroup(s);return`${s}${l.index++}`}_nameGroup(s){var l,m;if(!((m=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||m===void 0)&&m.has(s)||this._prefixes&&!this._prefixes.has(s))throw new Error(`CodeGen: prefix "${s}" is not allowed in this scope`);return this._names[s]={prefix:s,index:0}}};e.Scope=o;var i=class extends t.Name{constructor(s,l){super(l),this.prefix=s}setValue(s,{property:l,itemIndex:m}){this.value=s,this.scopePath=(0,t._)`.${new t.Name(l)}[${m}]`}};e.ValueScopeName=i;let a=(0,t._)`\n`;var c=class extends o{constructor(s){super(s),this._values={},this._scope=s.scope,this.opts={...s,_n:s.lines?a:t.nil}}get(){return this._scope}name(s){return new i(s,this._newName(s))}value(s,l){var m;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let h=this.toName(s),{prefix:z}=h,R=(m=l.key)!==null&&m!==void 0?m:l.ref,v=this._values[z];if(v){let d=v.get(R);if(d)return d}else v=this._values[z]=new Map;v.set(R,h);let b=this._scope[z]||(this._scope[z]=[]),g=b.length;return b[g]=l.ref,h.setValue(l,{property:z,itemIndex:g}),h}getValue(s,l){let m=this._values[s];if(m)return m.get(l)}scopeRefs(s,l=this._values){return this._reduceValues(l,m=>{if(m.scopePath===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return(0,t._)`${s}${m.scopePath}`})}scopeCode(s=this._values,l,m){return this._reduceValues(s,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},l,m)}_reduceValues(s,l,m={},h){let z=t.nil;for(let R in s){let v=s[R];if(!v)continue;let b=m[R]=m[R]||new Map;v.forEach(g=>{if(b.has(g))return;b.set(g,n.Started);let d=l(g);if(d){let _=this.opts.es5?e.varKinds.var:e.varKinds.const;z=(0,t._)`${z}${_} ${g} = ${d};${this.opts._n}`}else if(d=h?.(g))z=(0,t._)`${z}${d}${this.opts._n}`;else throw new r(g);b.set(g,n.Completed)})}return z}};e.ValueScope=c})),de=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=is(),r=_h();var n=is();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=_h();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};var i=class{optimizeNodes(){return this}optimizeNames($,P){return this}},a=class extends i{constructor($,P,N){super(),this.varKind=$,this.name=P,this.rhs=N}render({es5:$,_n:P}){let N=$?r.varKinds.var:this.varKind,H=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${H};`+P}optimizeNames($,P){if($[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,$,P)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},c=class extends i{constructor($,P,N){super(),this.lhs=$,this.rhs=P,this.sideEffects=N}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,P){if(!(this.lhs instanceof t.Name&&!$[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,$,P),this}get names(){return Y(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},s=class extends c{constructor($,P,N,H){super($,N,H),this.op=P}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}},l=class extends i{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}},m=class extends i{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}},h=class extends i{constructor($){super(),this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}},z=class extends i{constructor($){super(),this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,P){return this.code=K(this.code,$,P),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},R=class extends i{constructor($=[]){super(),this.nodes=$}render($){return this.nodes.reduce((P,N)=>P+N.render($),"")}optimizeNodes(){let{nodes:$}=this,P=$.length;for(;P--;){let N=$[P].optimizeNodes();Array.isArray(N)?$.splice(P,1,...N):N?$[P]=N:$.splice(P,1)}return $.length>0?this:void 0}optimizeNames($,P){let{nodes:N}=this,H=N.length;for(;H--;){let te=N[H];te.optimizeNames($,P)||(fe($,te.names),N.splice(H,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce(($,P)=>D($,P.names),{})}},v=class extends R{render($){return"{"+$._n+super.render($)+"}"+$._n}},b=class extends R{},g=class extends v{};g.kind="else";var d=class os extends v{constructor(P,N){super(N),this.condition=P}render(P){let N=`if(${this.condition})`+super.render(P);return this.else&&(N+="else "+this.else.render(P)),N}optimizeNodes(){super.optimizeNodes();let P=this.condition;if(P===!0)return this.nodes;let N=this.else;if(N){let H=N.optimizeNodes();N=this.else=Array.isArray(H)?new g(H):H}if(N)return P===!1?N instanceof os?N:N.nodes:this.nodes.length?this:new os(Te(P),N instanceof os?[N]:N.nodes);if(!(P===!1||!this.nodes.length))return this}optimizeNames(P,N){var H;if(this.else=(H=this.else)===null||H===void 0?void 0:H.optimizeNames(P,N),!!(super.optimizeNames(P,N)||this.else))return this.condition=K(this.condition,P,N),this}get names(){let P=super.names;return Y(P,this.condition),this.else&&D(P,this.else.names),P}};d.kind="if";var _=class extends v{};_.kind="for";var p=class extends _{constructor($){super(),this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,P){if(super.optimizeNames($,P))return this.iteration=K(this.iteration,$,P),this}get names(){return D(super.names,this.iteration.names)}},S=class extends _{constructor($,P,N,H){super(),this.varKind=$,this.name=P,this.from=N,this.to=H}render($){let P=$.es5?r.varKinds.var:this.varKind,{name:N,from:H,to:te}=this;return`for(${P} ${N}=${H}; ${N}<${te}; ${N}++)`+super.render($)}get names(){return Y(Y(super.names,this.from),this.to)}},w=class extends _{constructor($,P,N,H){super(),this.loop=$,this.varKind=P,this.name=N,this.iterable=H}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,P){if(super.optimizeNames($,P))return this.iterable=K(this.iterable,$,P),this}get names(){return D(super.names,this.iterable.names)}},y=class extends v{constructor($,P,N){super(),this.name=$,this.args=P,this.async=N}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}};y.kind="func";var f=class extends R{render($){return"return "+super.render($)}};f.kind="return";var T=class extends v{render($){let P="try"+super.render($);return this.catch&&(P+=this.catch.render($)),this.finally&&(P+=this.finally.render($)),P}optimizeNodes(){var $,P;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(P=this.finally)===null||P===void 0||P.optimizeNodes(),this}optimizeNames($,P){var N,H;return super.optimizeNames($,P),(N=this.catch)===null||N===void 0||N.optimizeNames($,P),(H=this.finally)===null||H===void 0||H.optimizeNames($,P),this}get names(){let $=super.names;return this.catch&&D($,this.catch.names),this.finally&&D($,this.finally.names),$}},A=class extends v{constructor($){super(),this.error=$}render($){return`catch(${this.error})`+super.render($)}};A.kind="catch";var F=class extends v{render($){return"finally"+super.render($)}};F.kind="finally";var M=class{constructor($,P={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...P,_n:P.lines?` +`:""},this._extScope=$,this._scope=new r.Scope({parent:$}),this._nodes=[new b]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,P){let N=this._extScope.value($,P);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue($,P){return this._extScope.getValue($,P)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,P,N,H){let te=this._scope.toName(P);return N!==void 0&&H&&(this._constants[te.str]=N),this._leafNode(new a($,te,N)),te}const($,P,N){return this._def(r.varKinds.const,$,P,N)}let($,P,N){return this._def(r.varKinds.let,$,P,N)}var($,P,N){return this._def(r.varKinds.var,$,P,N)}assign($,P,N){return this._leafNode(new c($,P,N))}add($,P){return this._leafNode(new s($,e.operators.ADD,P))}code($){return typeof $=="function"?$():$!==t.nil&&this._leafNode(new z($)),this}object(...$){let P=["{"];for(let[N,H]of $)P.length>1&&P.push(","),P.push(N),(N!==H||this.opts.es5)&&(P.push(":"),(0,t.addCodeArg)(P,H));return P.push("}"),new t._Code(P)}if($,P,N){if(this._blockNode(new d($)),P&&N)this.code(P).else().code(N).endIf();else if(P)this.code(P).endIf();else if(N)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new d($))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(d,g)}_for($,P){return this._blockNode($),P&&this.code(P).endFor(),this}for($,P){return this._for(new p($),P)}forRange($,P,N,H,te=this.opts.es5?r.varKinds.var:r.varKinds.let){let pe=this._scope.toName($);return this._for(new S(te,pe,P,N),()=>H(pe))}forOf($,P,N,H=r.varKinds.const){let te=this._scope.toName($);if(this.opts.es5){let pe=P instanceof t.Name?P:this.var("_arr",P);return this.forRange("_i",0,(0,t._)`${pe}.length`,ae=>{this.var(te,(0,t._)`${pe}[${ae}]`),N(te)})}return this._for(new w("of",H,te,P),()=>N(te))}forIn($,P,N,H=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf($,(0,t._)`Object.keys(${P})`,N);let te=this._scope.toName($);return this._for(new w("in",H,te,P),()=>N(te))}endFor(){return this._endBlockNode(_)}label($){return this._leafNode(new l($))}break($){return this._leafNode(new m($))}return($){let P=new f;if(this._blockNode(P),this.code($),P.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(f)}try($,P,N){if(!P&&!N)throw new Error('CodeGen: "try" without "catch" and "finally"');let H=new T;if(this._blockNode(H),this.code($),P){let te=this.name("e");this._currNode=H.catch=new A(te),P(te)}return N&&(this._currNode=H.finally=new F,this.code(N)),this._endBlockNode(A,F)}throw($){return this._leafNode(new h($))}block($,P){return this._blockStarts.push(this._nodes.length),$&&this.code($).endBlock(P),this}endBlock($){let P=this._blockStarts.pop();if(P===void 0)throw new Error("CodeGen: not in self-balancing block");let N=this._nodes.length-P;if(N<0||$!==void 0&&N!==$)throw new Error(`CodeGen: wrong number of nodes: ${N} vs ${$} expected`);return this._nodes.length=P,this}func($,P=t.nil,N,H){return this._blockNode(new y($,P,N)),H&&this.code(H).endFunc(),this}endFunc(){return this._endBlockNode(y)}optimize($=1){for(;$-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,P){let N=this._currNode;if(N instanceof $||P&&N instanceof P)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${P?`${$.kind}/${P.kind}`:$.kind}"`)}_elseNode($){let P=this._currNode;if(!(P instanceof d))throw new Error('CodeGen: "else" without "if"');return this._currNode=P.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let P=this._nodes;P[P.length-1]=$}};e.CodeGen=M;function D($,P){for(let N in P)$[N]=($[N]||0)+(P[N]||0);return $}function Y($,P){return P instanceof t._CodeOrName?D($,P.names):$}function K($,P,N){if($ instanceof t.Name)return H($);if(!te($))return $;return new t._Code($._items.reduce((pe,ae)=>(ae instanceof t.Name&&(ae=H(ae)),ae instanceof t._Code?pe.push(...ae._items):pe.push(ae),pe),[]));function H(pe){let ae=N[pe.str];return ae===void 0||P[pe.str]!==1?pe:(delete P[pe.str],ae)}function te(pe){return pe instanceof t._Code&&pe._items.some(ae=>ae instanceof t.Name&&P[ae.str]===1&&N[ae.str]!==void 0)}}function fe($,P){for(let N in P)$[N]=($[N]||0)-(P[N]||0)}function Te($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:(0,t._)`!${V($)}`}e.not=Te;let ze=x(e.operators.AND);function Ce(...$){return $.reduce(ze)}e.and=Ce;let ve=x(e.operators.OR);function k(...$){return $.reduce(ve)}e.or=k;function x($){return(P,N)=>P===t.nil?N:N===t.nil?P:(0,t._)`${V(P)} ${$} ${V(N)}`}function V($){return $ instanceof t.Name?$:(0,t._)`(${$})`}})),_e=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=de(),r=is();function n(y){let f={};for(let T of y)f[T]=!0;return f}e.toHash=n;function o(y,f){return typeof f=="boolean"?f:Object.keys(f).length===0?!0:(i(y,f),!a(f,y.self.RULES.all))}e.alwaysValidSchema=o;function i(y,f=y.schema){let{opts:T,self:A}=y;if(!T.strictSchema||typeof f=="boolean")return;let F=A.RULES.keywords;for(let M in f)F[M]||w(y,`unknown keyword: "${M}"`)}e.checkUnknownRules=i;function a(y,f){if(typeof y=="boolean")return!y;for(let T in y)if(f[T])return!0;return!1}e.schemaHasRules=a;function c(y,f){if(typeof y=="boolean")return!y;for(let T in y)if(T!=="$ref"&&f.all[T])return!0;return!1}e.schemaHasRulesButRef=c;function s({topSchemaRef:y,schemaPath:f},T,A,F){if(!F){if(typeof T=="number"||typeof T=="boolean")return T;if(typeof T=="string")return(0,t._)`${T}`}return(0,t._)`${y}${f}${(0,t.getProperty)(A)}`}e.schemaRefOrVal=s;function l(y){return z(decodeURIComponent(y))}e.unescapeFragment=l;function m(y){return encodeURIComponent(h(y))}e.escapeFragment=m;function h(y){return typeof y=="number"?`${y}`:y.replace(/~/g,"~0").replace(/\//g,"~1")}e.escapeJsonPointer=h;function z(y){return y.replace(/~1/g,"/").replace(/~0/g,"~")}e.unescapeJsonPointer=z;function R(y,f){if(Array.isArray(y))for(let T of y)f(T);else f(y)}e.eachItem=R;function v({mergeNames:y,mergeToName:f,mergeValues:T,resultToName:A}){return(F,M,D,Y)=>{let K=D===void 0?M:D instanceof t.Name?(M instanceof t.Name?y(F,M,D):f(F,M,D),D):M instanceof t.Name?(f(F,D,M),M):T(M,D);return Y===t.Name&&!(K instanceof t.Name)?A(F,K):K}}e.mergeEvaluated={props:v({mergeNames:(y,f,T)=>y.if((0,t._)`${T} !== true && ${f} !== undefined`,()=>{y.if((0,t._)`${f} === true`,()=>y.assign(T,!0),()=>y.assign(T,(0,t._)`${T} || {}`).code((0,t._)`Object.assign(${T}, ${f})`))}),mergeToName:(y,f,T)=>y.if((0,t._)`${T} !== true`,()=>{f===!0?y.assign(T,!0):(y.assign(T,(0,t._)`${T} || {}`),g(y,T,f))}),mergeValues:(y,f)=>y===!0?!0:{...y,...f},resultToName:b}),items:v({mergeNames:(y,f,T)=>y.if((0,t._)`${T} !== true && ${f} !== undefined`,()=>y.assign(T,(0,t._)`${f} === true ? true : ${T} > ${f} ? ${T} : ${f}`)),mergeToName:(y,f,T)=>y.if((0,t._)`${T} !== true`,()=>y.assign(T,f===!0?!0:(0,t._)`${T} > ${f} ? ${T} : ${f}`)),mergeValues:(y,f)=>y===!0?!0:Math.max(y,f),resultToName:(y,f)=>y.var("items",f)})};function b(y,f){if(f===!0)return y.var("props",!0);let T=y.var("props",(0,t._)`{}`);return f!==void 0&&g(y,T,f),T}e.evaluatedPropsToName=b;function g(y,f,T){Object.keys(T).forEach(A=>y.assign((0,t._)`${f}${(0,t.getProperty)(A)}`,!0))}e.setEvaluated=g;let d={};function _(y,f){return y.scopeValue("func",{ref:f,code:d[f.code]||(d[f.code]=new r._Code(f.code))})}e.useFunc=_;var p;(function(y){y[y.Num=0]="Num",y[y.Str=1]="Str"})(p||(e.Type=p={}));function S(y,f,T){if(y instanceof t.Name){let A=f===p.Num;return T?A?(0,t._)`"[" + ${y} + "]"`:(0,t._)`"['" + ${y} + "']"`:A?(0,t._)`"/" + ${y}`:(0,t._)`"/" + ${y}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return T?(0,t.getProperty)(y).toString():"/"+h(y)}e.getErrorPath=S;function w(y,f,T=y.opts.strictSchema){if(T){if(f=`strict mode: ${f}`,T===!0)throw new Error(f);y.self.logger.warn(f)}}e.checkStrictMode=w})),dt=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};e.default=r})),ss=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=de(),r=_e(),n=dt();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:d})=>d?(0,t.str)`"${g}" keyword must be ${d} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function o(g,d=e.keywordError,_,p){let{it:S}=g,{gen:w,compositeRule:y,allErrors:f}=S,T=h(g,d,_);p??(y||f)?s(w,T):l(S,(0,t._)`[${T}]`)}e.reportError=o;function i(g,d=e.keywordError,_){let{it:p}=g,{gen:S,compositeRule:w,allErrors:y}=p;s(S,h(g,d,_)),w||y||l(p,n.default.vErrors)}e.reportExtraError=i;function a(g,d){g.assign(n.default.errors,d),g.if((0,t._)`${n.default.vErrors} !== null`,()=>g.if(d,()=>g.assign((0,t._)`${n.default.vErrors}.length`,d),()=>g.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function c({gen:g,keyword:d,schemaValue:_,data:p,errsCount:S,it:w}){if(S===void 0)throw new Error("ajv implementation error");let y=g.name("err");g.forRange("i",S,n.default.errors,f=>{g.const(y,(0,t._)`${n.default.vErrors}[${f}]`),g.if((0,t._)`${y}.instancePath === undefined`,()=>g.assign((0,t._)`${y}.instancePath`,(0,t.strConcat)(n.default.instancePath,w.errorPath))),g.assign((0,t._)`${y}.schemaPath`,(0,t.str)`${w.errSchemaPath}/${d}`),w.opts.verbose&&(g.assign((0,t._)`${y}.schema`,_),g.assign((0,t._)`${y}.data`,p))})}e.extendErrors=c;function s(g,d){let _=g.const("err",d);g.if((0,t._)`${n.default.vErrors} === null`,()=>g.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),g.code((0,t._)`${n.default.errors}++`)}function l(g,d){let{gen:_,validateName:p,schemaEnv:S}=g;S.$async?_.throw((0,t._)`new ${g.ValidationError}(${d})`):(_.assign((0,t._)`${p}.errors`,d),_.return(!1))}let m={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function h(g,d,_){let{createErrors:p}=g.it;return p===!1?(0,t._)`{}`:z(g,d,_)}function z(g,d,_={}){let{gen:p,it:S}=g,w=[R(S,_),v(g,_)];return b(g,d,w),p.object(...w)}function R({errorPath:g},{instancePath:d}){let _=d?(0,t.str)`${g}${(0,r.getErrorPath)(d,r.Type.Str)}`:g;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function v({keyword:g,it:{errSchemaPath:d}},{schemaPath:_,parentSchema:p}){let S=p?d:(0,t.str)`${d}/${g}`;return _&&(S=(0,t.str)`${S}${(0,r.getErrorPath)(_,r.Type.Str)}`),[m.schemaPath,S]}function b(g,{params:d,message:_},p){let{keyword:S,data:w,schemaValue:y,it:f}=g,{opts:T,propertyName:A,topSchemaRef:F,schemaPath:M}=f;p.push([m.keyword,S],[m.params,typeof d=="function"?d(g):d||(0,t._)`{}`]),T.messages&&p.push([m.message,typeof _=="function"?_(g):_]),T.verbose&&p.push([m.schema,y],[m.parentSchema,(0,t._)`${F}${M}`],[n.default.data,w]),A&&p.push([m.propertyName,A])}})),DS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=ss(),r=de(),n=dt(),o={message:"boolean schema is false"};function i(s){let{gen:l,schema:m,validateName:h}=s;m===!1?c(s,!1):typeof m=="object"&&m.$async===!0?l.return(n.default.data):(l.assign((0,r._)`${h}.errors`,null),l.return(!0))}e.topBoolOrEmptySchema=i;function a(s,l){let{gen:m,schema:h}=s;h===!1?(m.var(l,!1),c(s)):m.var(l,!0)}e.boolOrEmptySchema=a;function c(s,l){let{gen:m,data:h}=s,z={gen:m,keyword:"false schema",data:h,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:s};(0,t.reportError)(z,o,void 0,l)}})),Sh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set(["string","number","integer","boolean","null","object","array"]);function r(o){return typeof o=="string"&&t.has(o)}e.isJSONType=r;function n(){let o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=n})),yh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:o,self:i},a){let c=i.RULES.types[a];return c&&c!==!0&&r(o,c)}e.schemaHasRulesForType=t;function r(o,i){return i.rules.some(a=>n(o,a))}e.shouldUseGroup=r;function n(o,i){var a;return o[i.keyword]!==void 0||((a=i.definition.implements)===null||a===void 0?void 0:a.some(c=>o[c]!==void 0))}e.shouldUseRule=n})),as=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Sh(),r=yh(),n=ss(),o=de(),i=_e();var a;(function(p){p[p.Correct=0]="Correct",p[p.Wrong=1]="Wrong"})(a||(e.DataType=a={}));function c(p){let S=s(p.type);if(S.includes("null")){if(p.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!S.length&&p.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');p.nullable===!0&&S.push("null")}return S}e.getSchemaTypes=c;function s(p){let S=Array.isArray(p)?p:p?[p]:[];if(S.every(t.isJSONType))return S;throw new Error("type must be JSONType or JSONType[]: "+S.join(","))}e.getJSONTypes=s;function l(p,S){let{gen:w,data:y,opts:f}=p,T=h(S,f.coerceTypes),A=S.length>0&&!(T.length===0&&S.length===1&&(0,r.schemaHasRulesForType)(p,S[0]));if(A){let F=b(S,y,f.strictNumbers,a.Wrong);w.if(F,()=>{T.length?z(p,S,T):d(p)})}return A}e.coerceAndCheckDataType=l;let m=new Set(["string","number","integer","boolean","null"]);function h(p,S){return S?p.filter(w=>m.has(w)||S==="array"&&w==="array"):[]}function z(p,S,w){let{gen:y,data:f,opts:T}=p,A=y.let("dataType",(0,o._)`typeof ${f}`),F=y.let("coerced",(0,o._)`undefined`);T.coerceTypes==="array"&&y.if((0,o._)`${A} == 'object' && Array.isArray(${f}) && ${f}.length == 1`,()=>y.assign(f,(0,o._)`${f}[0]`).assign(A,(0,o._)`typeof ${f}`).if(b(S,f,T.strictNumbers),()=>y.assign(F,f))),y.if((0,o._)`${F} !== undefined`);for(let D of w)(m.has(D)||D==="array"&&T.coerceTypes==="array")&&M(D);y.else(),d(p),y.endIf(),y.if((0,o._)`${F} !== undefined`,()=>{y.assign(f,F),R(p,F)});function M(D){switch(D){case"string":y.elseIf((0,o._)`${A} == "number" || ${A} == "boolean"`).assign(F,(0,o._)`"" + ${f}`).elseIf((0,o._)`${f} === null`).assign(F,(0,o._)`""`);return;case"number":y.elseIf((0,o._)`${A} == "boolean" || ${f} === null + || (${A} == "string" && ${f} && ${f} == +${f})`).assign(F,(0,o._)`+${f}`);return;case"integer":y.elseIf((0,o._)`${A} === "boolean" || ${f} === null + || (${A} === "string" && ${f} && ${f} == +${f} && !(${f} % 1))`).assign(F,(0,o._)`+${f}`);return;case"boolean":y.elseIf((0,o._)`${f} === "false" || ${f} === 0 || ${f} === null`).assign(F,!1).elseIf((0,o._)`${f} === "true" || ${f} === 1`).assign(F,!0);return;case"null":y.elseIf((0,o._)`${f} === "" || ${f} === 0 || ${f} === false`),y.assign(F,null);return;case"array":y.elseIf((0,o._)`${A} === "string" || ${A} === "number" + || ${A} === "boolean" || ${f} === null`).assign(F,(0,o._)`[${f}]`)}}}function R({gen:p,parentData:S,parentDataProperty:w},y){p.if((0,o._)`${S} !== undefined`,()=>p.assign((0,o._)`${S}[${w}]`,y))}function v(p,S,w,y=a.Correct){let f=y===a.Correct?o.operators.EQ:o.operators.NEQ,T;switch(p){case"null":return(0,o._)`${S} ${f} null`;case"array":T=(0,o._)`Array.isArray(${S})`;break;case"object":T=(0,o._)`${S} && typeof ${S} == "object" && !Array.isArray(${S})`;break;case"integer":T=A((0,o._)`!(${S} % 1) && !isNaN(${S})`);break;case"number":T=A();break;default:return(0,o._)`typeof ${S} ${f} ${p}`}return y===a.Correct?T:(0,o.not)(T);function A(F=o.nil){return(0,o.and)((0,o._)`typeof ${S} == "number"`,F,w?(0,o._)`isFinite(${S})`:o.nil)}}e.checkDataType=v;function b(p,S,w,y){if(p.length===1)return v(p[0],S,w,y);let f,T=(0,i.toHash)(p);if(T.array&&T.object){let A=(0,o._)`typeof ${S} != "object"`;f=T.null?A:(0,o._)`!${S} || ${A}`,delete T.null,delete T.array,delete T.object}else f=o.nil;T.number&&delete T.integer;for(let A in T)f=(0,o.and)(f,v(A,S,w,y));return f}e.checkDataTypes=b;let g={message:({schema:p})=>`must be ${p}`,params:({schema:p,schemaValue:S})=>typeof p=="string"?(0,o._)`{type: ${p}}`:(0,o._)`{type: ${S}}`};function d(p){let S=_(p);(0,n.reportError)(S,g)}e.reportTypeError=d;function _(p){let{gen:S,data:w,schema:y}=p,f=(0,i.schemaRefOrVal)(p,y,"type");return{gen:S,keyword:"type",data:w,schema:y.type,schemaCode:f,schemaValue:f,parentSchema:y,params:{},it:p}}})),VS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=de(),r=_e();function n(i,a){let{properties:c,items:s}=i.schema;if(a==="object"&&c)for(let l in c)o(i,l,c[l].default);else a==="array"&&Array.isArray(s)&&s.forEach((l,m)=>o(i,m,l.default))}e.assignDefaults=n;function o(i,a,c){let{gen:s,compositeRule:l,data:m,opts:h}=i;if(c===void 0)return;let z=(0,t._)`${m}${(0,t.getProperty)(a)}`;if(l){(0,r.checkStrictMode)(i,`default is ignored for: ${z}`);return}let R=(0,t._)`${z} === undefined`;h.useDefaults==="empty"&&(R=(0,t._)`${R} || ${z} === null || ${z} === ""`),s.if(R,(0,t._)`${z} = ${(0,t.stringify)(c)}`)}})),mt=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=de(),r=_e(),n=dt(),o=_e();function i(p,S){let{gen:w,data:y,it:f}=p;w.if(h(w,y,S,f.opts.ownProperties),()=>{p.setParams({missingProperty:(0,t._)`${S}`},!0),p.error()})}e.checkReportMissingProp=i;function a({gen:p,data:S,it:{opts:w}},y,f){return(0,t.or)(...y.map(T=>(0,t.and)(h(p,S,T,w.ownProperties),(0,t._)`${f} = ${T}`)))}e.checkMissingProp=a;function c(p,S){p.setParams({missingProperty:S},!0),p.error()}e.reportMissingProp=c;function s(p){return p.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=s;function l(p,S,w){return(0,t._)`${s(p)}.call(${S}, ${w})`}e.isOwnProperty=l;function m(p,S,w,y){let f=(0,t._)`${S}${(0,t.getProperty)(w)} !== undefined`;return y?(0,t._)`${f} && ${l(p,S,w)}`:f}e.propertyInData=m;function h(p,S,w,y){let f=(0,t._)`${S}${(0,t.getProperty)(w)} === undefined`;return y?(0,t.or)(f,(0,t.not)(l(p,S,w))):f}e.noPropertyInData=h;function z(p){return p?Object.keys(p).filter(S=>S!=="__proto__"):[]}e.allSchemaProperties=z;function R(p,S){return z(S).filter(w=>!(0,r.alwaysValidSchema)(p,S[w]))}e.schemaProperties=R;function v({schemaCode:p,data:S,it:{gen:w,topSchemaRef:y,schemaPath:f,errorPath:T},it:A},F,M,D){let Y=D?(0,t._)`${p}, ${S}, ${y}${f}`:S,K=[[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,T)],[n.default.parentData,A.parentData],[n.default.parentDataProperty,A.parentDataProperty],[n.default.rootData,n.default.rootData]];A.opts.dynamicRef&&K.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let fe=(0,t._)`${Y}, ${w.object(...K)}`;return M!==t.nil?(0,t._)`${F}.call(${M}, ${fe})`:(0,t._)`${F}(${fe})`}e.callValidateCode=v;let b=(0,t._)`new RegExp`;function g({gen:p,it:{opts:S}},w){let y=S.unicodeRegExp?"u":"",{regExp:f}=S.code,T=f(w,y);return p.scopeValue("pattern",{key:T.toString(),ref:T,code:(0,t._)`${f.code==="new RegExp"?b:(0,o.useFunc)(p,f)}(${w}, ${y})`})}e.usePattern=g;function d(p){let{gen:S,data:w,keyword:y,it:f}=p,T=S.name("valid");if(f.allErrors){let F=S.let("valid",!0);return A(()=>S.assign(F,!1)),F}return S.var(T,!0),A(()=>S.break()),T;function A(F){let M=S.const("len",(0,t._)`${w}.length`);S.forRange("i",0,M,D=>{p.subschema({keyword:y,dataProp:D,dataPropType:r.Type.Num},T),S.if((0,t.not)(T),F)})}}e.validateArray=d;function _(p){let{gen:S,schema:w,keyword:y,it:f}=p;if(!Array.isArray(w))throw new Error("ajv implementation error");if(w.some(F=>(0,r.alwaysValidSchema)(f,F))&&!f.opts.unevaluated)return;let T=S.let("valid",!1),A=S.name("_valid");S.block(()=>w.forEach((F,M)=>{let D=p.subschema({keyword:y,schemaProp:M,compositeRule:!0},A);S.assign(T,(0,t._)`${T} || ${A}`),p.mergeValidEvaluated(D,A)||S.if((0,t.not)(T))})),p.result(T,()=>p.reset(),()=>p.error(!0))}e.validateUnion=_})),ZS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=de(),r=dt(),n=mt(),o=ss();function i(R,v){let{gen:b,keyword:g,schema:d,parentSchema:_,it:p}=R,S=v.macro.call(p.self,d,_,p),w=m(b,g,S);p.opts.validateSchema!==!1&&p.self.validateSchema(S,!0);let y=b.name("valid");R.subschema({schema:S,schemaPath:t.nil,errSchemaPath:`${p.errSchemaPath}/${g}`,topSchemaRef:w,compositeRule:!0},y),R.pass(y,()=>R.error(!0))}e.macroKeywordCode=i;function a(R,v){var b;let{gen:g,keyword:d,schema:_,parentSchema:p,$data:S,it:w}=R;l(w,v);let y=m(g,d,!S&&v.compile?v.compile.call(w.self,_,p,w):v.validate),f=g.let("valid");R.block$data(f,T),R.ok((b=v.valid)!==null&&b!==void 0?b:f);function T(){if(v.errors===!1)M(),v.modifying&&c(R),D(()=>R.error());else{let Y=v.async?A():F();v.modifying&&c(R),D(()=>s(R,Y))}}function A(){let Y=g.let("ruleErrs",null);return g.try(()=>M((0,t._)`await `),K=>g.assign(f,!1).if((0,t._)`${K} instanceof ${w.ValidationError}`,()=>g.assign(Y,(0,t._)`${K}.errors`),()=>g.throw(K))),Y}function F(){let Y=(0,t._)`${y}.errors`;return g.assign(Y,null),M(t.nil),Y}function M(Y=v.async?(0,t._)`await `:t.nil){let K=w.opts.passContext?r.default.this:r.default.self,fe=!("compile"in v&&!S||v.schema===!1);g.assign(f,(0,t._)`${Y}${(0,n.callValidateCode)(R,y,K,fe)}`,v.modifying)}function D(Y){var K;g.if((0,t.not)((K=v.valid)!==null&&K!==void 0?K:f),Y)}}e.funcKeywordCode=a;function c(R){let{gen:v,data:b,it:g}=R;v.if(g.parentData,()=>v.assign(b,(0,t._)`${g.parentData}[${g.parentDataProperty}]`))}function s(R,v){let{gen:b}=R;b.if((0,t._)`Array.isArray(${v})`,()=>{b.assign(r.default.vErrors,(0,t._)`${r.default.vErrors} === null ? ${v} : ${r.default.vErrors}.concat(${v})`).assign(r.default.errors,(0,t._)`${r.default.vErrors}.length`),(0,o.extendErrors)(R)},()=>R.error())}function l({schemaEnv:R},v){if(v.async&&!R.$async)throw new Error("async keyword in sync schema")}function m(R,v,b){if(b===void 0)throw new Error(`keyword "${v}" failed to compile`);return R.scopeValue("keyword",typeof b=="function"?{ref:b}:{ref:b,code:(0,t.stringify)(b)})}function h(R,v,b=!1){return!v.length||v.some(g=>g==="array"?Array.isArray(R):g==="object"?R&&typeof R=="object"&&!Array.isArray(R):typeof R==g||b&&typeof R>"u")}e.validSchemaType=h;function z({schema:R,opts:v,self:b,errSchemaPath:g},d,_){if(Array.isArray(d.keyword)?!d.keyword.includes(_):d.keyword!==_)throw new Error("ajv implementation error");let p=d.dependencies;if(p?.some(S=>!Object.prototype.hasOwnProperty.call(R,S)))throw new Error(`parent schema must have dependencies of ${_}: ${p.join(",")}`);if(d.validateSchema&&!d.validateSchema(R[_])){let S=`keyword "${_}" value is invalid at path "${g}": `+b.errorsText(d.validateSchema.errors);if(v.validateSchema==="log")b.logger.error(S);else throw new Error(S)}}e.validateKeywordUsage=z})),FS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=de(),r=_e();function n(a,{keyword:c,schemaProp:s,schema:l,schemaPath:m,errSchemaPath:h,topSchemaRef:z}){if(c!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(c!==void 0){let R=a.schema[c];return s===void 0?{schema:R,schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(c)}`,errSchemaPath:`${a.errSchemaPath}/${c}`}:{schema:R[s],schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(c)}${(0,t.getProperty)(s)}`,errSchemaPath:`${a.errSchemaPath}/${c}/${(0,r.escapeFragment)(s)}`}}if(l!==void 0){if(m===void 0||h===void 0||z===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:m,topSchemaRef:z,errSchemaPath:h}}throw new Error('either "keyword" or "schema" must be passed')}e.getSubschema=n;function o(a,c,{dataProp:s,dataPropType:l,data:m,dataTypes:h,propertyName:z}){if(m!==void 0&&s!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:R}=c;if(s!==void 0){let{errorPath:b,dataPathArr:g,opts:d}=c;v(R.let("data",(0,t._)`${c.data}${(0,t.getProperty)(s)}`,!0)),a.errorPath=(0,t.str)`${b}${(0,r.getErrorPath)(s,l,d.jsPropertySyntax)}`,a.parentDataProperty=(0,t._)`${s}`,a.dataPathArr=[...g,a.parentDataProperty]}m!==void 0&&(v(m instanceof t.Name?m:R.let("data",m,!0)),z!==void 0&&(a.propertyName=z)),h&&(a.dataTypes=h);function v(b){a.data=b,a.dataLevel=c.dataLevel+1,a.dataTypes=[],c.definedProperties=new Set,a.parentData=c.data,a.dataNames=[...c.dataNames,b]}}e.extendSubschemaData=o;function i(a,{jtdDiscriminator:c,jtdMetadata:s,compositeRule:l,createErrors:m,allErrors:h}){l!==void 0&&(a.compositeRule=l),m!==void 0&&(a.createErrors=m),h!==void 0&&(a.allErrors=h),a.jtdDiscriminator=c,a.jtdMetadata=s}e.extendSubschemaMode=i})),bh=L(((e,t)=>{t.exports=function r(n,o){if(n===o)return!0;if(n&&o&&typeof n=="object"&&typeof o=="object"){if(n.constructor!==o.constructor)return!1;var i,a,c;if(Array.isArray(n)){if(i=n.length,i!=o.length)return!1;for(a=i;a--!==0;)if(!r(n[a],o[a]))return!1;return!0}if(n.constructor===RegExp)return n.source===o.source&&n.flags===o.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===o.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===o.toString();if(c=Object.keys(n),i=c.length,i!==Object.keys(o).length)return!1;for(a=i;a--!==0;)if(!Object.prototype.hasOwnProperty.call(o,c[a]))return!1;for(a=i;a--!==0;){var s=c[a];if(!r(n[s],o[s]))return!1}return!0}return n!==n&&o!==o}})),HS=L(((e,t)=>{var r=t.exports=function(i,a,c){typeof a=="function"&&(c=a,a={}),c=a.cb||c;var s=typeof c=="function"?c:c.pre||function(){},l=c.post||function(){};n(a,s,l,i,"",i)};r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},r.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};function n(i,a,c,s,l,m,h,z,R,v){if(s&&typeof s=="object"&&!Array.isArray(s)){a(s,l,m,h,z,R,v);for(var b in s){var g=s[b];if(Array.isArray(g)){if(b in r.arrayKeywords)for(var d=0;d{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=_e(),r=bh(),n=HS(),o=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function i(g,d=!0){return typeof g=="boolean"?!0:d===!0?!c(g):d?s(g)<=d:!1}e.inlineRef=i;let a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function c(g){for(let d in g){if(a.has(d))return!0;let _=g[d];if(Array.isArray(_)&&_.some(c)||typeof _=="object"&&c(_))return!0}return!1}function s(g){let d=0;for(let _ in g){if(_==="$ref")return 1/0;if(d++,!o.has(_)&&(typeof g[_]=="object"&&(0,t.eachItem)(g[_],p=>d+=s(p)),d===1/0))return 1/0}return d}function l(g,d="",_){return _!==!1&&(d=z(d)),m(g,g.parse(d))}e.getFullPath=l;function m(g,d){return g.serialize(d).split("#")[0]+"#"}e._getFullPath=m;let h=/#\/?$/;function z(g){return g?g.replace(h,""):""}e.normalizeId=z;function R(g,d,_){return _=z(_),g.resolve(d,_)}e.resolveUrl=R;let v=/^[a-z_][-a-z0-9._]*$/i;function b(g,d){if(typeof g=="boolean")return{};let{schemaId:_,uriResolver:p}=this.opts,S=z(g[_]||d),w={"":S},y=l(p,S,!1),f={},T=new Set;return n(g,{allKeys:!0},(M,D,Y,K)=>{if(K===void 0)return;let fe=y+D,Te=w[K];typeof M[_]=="string"&&(Te=ze.call(this,M[_])),Ce.call(this,M.$anchor),Ce.call(this,M.$dynamicAnchor),w[D]=Te;function ze(ve){let k=this.opts.uriResolver.resolve;if(ve=z(Te?k(Te,ve):ve),T.has(ve))throw F(ve);T.add(ve);let x=this.refs[ve];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?A(M,x.schema,ve):ve!==z(fe)&&(ve[0]==="#"?(A(M,f[ve],ve),f[ve]=M):this.refs[ve]=fe),ve}function Ce(ve){if(typeof ve=="string"){if(!v.test(ve))throw new Error(`invalid anchor "${ve}"`);ze.call(this,`#${ve}`)}}}),f;function A(M,D,Y){if(D!==void 0&&!r(M,D))throw F(Y)}function F(M){return new Error(`reference "${M}" resolves to more than one schema`)}}e.getSchemaRefs=b})),Xr=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=DS(),r=as(),n=yh(),o=as(),i=VS(),a=ZS(),c=FS(),s=de(),l=dt(),m=cs(),h=_e(),z=ss();function R(I){if(y(I)&&(T(I),w(I))){d(I);return}v(I,()=>(0,t.topBoolOrEmptySchema)(I))}e.validateFunctionCode=R;function v({gen:I,validateName:C,schema:U,schemaEnv:oe,opts:ie},me){ie.code.es5?I.func(C,(0,s._)`${l.default.data}, ${l.default.valCxt}`,oe.$async,()=>{I.code((0,s._)`"use strict"; ${p(U,ie)}`),g(I,ie),I.code(me)}):I.func(C,(0,s._)`${l.default.data}, ${b(ie)}`,oe.$async,()=>I.code(p(U,ie)).code(me))}function b(I){return(0,s._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${I.dynamicRef?(0,s._)`, ${l.default.dynamicAnchors}={}`:s.nil}}={}`}function g(I,C){I.if(l.default.valCxt,()=>{I.var(l.default.instancePath,(0,s._)`${l.default.valCxt}.${l.default.instancePath}`),I.var(l.default.parentData,(0,s._)`${l.default.valCxt}.${l.default.parentData}`),I.var(l.default.parentDataProperty,(0,s._)`${l.default.valCxt}.${l.default.parentDataProperty}`),I.var(l.default.rootData,(0,s._)`${l.default.valCxt}.${l.default.rootData}`),C.dynamicRef&&I.var(l.default.dynamicAnchors,(0,s._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{I.var(l.default.instancePath,(0,s._)`""`),I.var(l.default.parentData,(0,s._)`undefined`),I.var(l.default.parentDataProperty,(0,s._)`undefined`),I.var(l.default.rootData,l.default.data),C.dynamicRef&&I.var(l.default.dynamicAnchors,(0,s._)`{}`)})}function d(I){let{schema:C,opts:U,gen:oe}=I;v(I,()=>{U.$comment&&C.$comment&&K(I),M(I),oe.let(l.default.vErrors,null),oe.let(l.default.errors,0),U.unevaluated&&_(I),A(I),fe(I)})}function _(I){let{gen:C,validateName:U}=I;I.evaluated=C.const("evaluated",(0,s._)`${U}.evaluated`),C.if((0,s._)`${I.evaluated}.dynamicProps`,()=>C.assign((0,s._)`${I.evaluated}.props`,(0,s._)`undefined`)),C.if((0,s._)`${I.evaluated}.dynamicItems`,()=>C.assign((0,s._)`${I.evaluated}.items`,(0,s._)`undefined`))}function p(I,C){let U=typeof I=="object"&&I[C.schemaId];return U&&(C.code.source||C.code.process)?(0,s._)`/*# sourceURL=${U} */`:s.nil}function S(I,C){if(y(I)&&(T(I),w(I))){f(I,C);return}(0,t.boolOrEmptySchema)(I,C)}function w({schema:I,self:C}){if(typeof I=="boolean")return!I;for(let U in I)if(C.RULES.all[U])return!0;return!1}function y(I){return typeof I.schema!="boolean"}function f(I,C){let{schema:U,gen:oe,opts:ie}=I;ie.$comment&&U.$comment&&K(I),D(I),Y(I);let me=oe.const("_errs",l.default.errors);A(I,me),oe.var(C,(0,s._)`${me} === ${l.default.errors}`)}function T(I){(0,h.checkUnknownRules)(I),F(I)}function A(I,C){if(I.opts.jtd)return ze(I,[],!1,C);let U=(0,r.getSchemaTypes)(I.schema);ze(I,U,!(0,r.coerceAndCheckDataType)(I,U),C)}function F(I){let{schema:C,errSchemaPath:U,opts:oe,self:ie}=I;C.$ref&&oe.ignoreKeywordsWithRef&&(0,h.schemaHasRulesButRef)(C,ie.RULES)&&ie.logger.warn(`$ref: keywords ignored in schema at path "${U}"`)}function M(I){let{schema:C,opts:U}=I;C.default!==void 0&&U.useDefaults&&U.strictSchema&&(0,h.checkStrictMode)(I,"default is ignored in the schema root")}function D(I){let C=I.schema[I.opts.schemaId];C&&(I.baseId=(0,m.resolveUrl)(I.opts.uriResolver,I.baseId,C))}function Y(I){if(I.schema.$async&&!I.schemaEnv.$async)throw new Error("async schema in sync schema")}function K({gen:I,schemaEnv:C,schema:U,errSchemaPath:oe,opts:ie}){let me=U.$comment;if(ie.$comment===!0)I.code((0,s._)`${l.default.self}.logger.log(${me})`);else if(typeof ie.$comment=="function"){let Ne=(0,s.str)`${oe}/$comment`,qe=I.scopeValue("root",{ref:C.root});I.code((0,s._)`${l.default.self}.opts.$comment(${me}, ${Ne}, ${qe}.schema)`)}}function fe(I){let{gen:C,schemaEnv:U,validateName:oe,ValidationError:ie,opts:me}=I;U.$async?C.if((0,s._)`${l.default.errors} === 0`,()=>C.return(l.default.data),()=>C.throw((0,s._)`new ${ie}(${l.default.vErrors})`)):(C.assign((0,s._)`${oe}.errors`,l.default.vErrors),me.unevaluated&&Te(I),C.return((0,s._)`${l.default.errors} === 0`))}function Te({gen:I,evaluated:C,props:U,items:oe}){U instanceof s.Name&&I.assign((0,s._)`${C}.props`,U),oe instanceof s.Name&&I.assign((0,s._)`${C}.items`,oe)}function ze(I,C,U,oe){let{gen:ie,schema:me,data:Ne,allErrors:qe,opts:Fe,self:Ae}=I,{RULES:Ie}=Ae;if(me.$ref&&(Fe.ignoreKeywordsWithRef||!(0,h.schemaHasRulesButRef)(me,Ie))){ie.block(()=>pe(I,"$ref",Ie.all.$ref.definition));return}Fe.jtd||ve(I,C),ie.block(()=>{for(let Ue of Ie.rules)nt(Ue);nt(Ie.post)});function nt(Ue){(0,n.shouldUseGroup)(me,Ue)&&(Ue.type?(ie.if((0,o.checkDataType)(Ue.type,Ne,Fe.strictNumbers)),Ce(I,Ue),C.length===1&&C[0]===Ue.type&&U&&(ie.else(),(0,o.reportTypeError)(I)),ie.endIf()):Ce(I,Ue),qe||ie.if((0,s._)`${l.default.errors} === ${oe||0}`))}}function Ce(I,C){let{gen:U,schema:oe,opts:{useDefaults:ie}}=I;ie&&(0,i.assignDefaults)(I,C.type),U.block(()=>{for(let me of C.rules)(0,n.shouldUseRule)(oe,me)&&pe(I,me.keyword,me.definition,C.type)})}function ve(I,C){I.schemaEnv.meta||!I.opts.strictTypes||(k(I,C),I.opts.allowUnionTypes||x(I,C),V(I,I.dataTypes))}function k(I,C){if(C.length){if(!I.dataTypes.length){I.dataTypes=C;return}C.forEach(U=>{P(I.dataTypes,U)||H(I,`type "${U}" not allowed by context "${I.dataTypes.join(",")}"`)}),N(I,C)}}function x(I,C){C.length>1&&!(C.length===2&&C.includes("null"))&&H(I,"use allowUnionTypes to allow union type keyword")}function V(I,C){let U=I.self.RULES.all;for(let oe in U){let ie=U[oe];if(typeof ie=="object"&&(0,n.shouldUseRule)(I.schema,ie)){let{type:me}=ie.definition;me.length&&!me.some(Ne=>$(C,Ne))&&H(I,`missing type "${me.join(",")}" for keyword "${oe}"`)}}}function $(I,C){return I.includes(C)||C==="number"&&I.includes("integer")}function P(I,C){return I.includes(C)||C==="integer"&&I.includes("number")}function N(I,C){let U=[];for(let oe of I.dataTypes)P(C,oe)?U.push(oe):C.includes("integer")&&oe==="number"&&U.push("integer");I.dataTypes=U}function H(I,C){let U=I.schemaEnv.baseId+I.errSchemaPath;C+=` at "${U}" (strictTypes)`,(0,h.checkStrictMode)(I,C,I.opts.strictTypes)}var te=class{constructor(I,C,U){if((0,a.validateKeywordUsage)(I,C,U),this.gen=I.gen,this.allErrors=I.allErrors,this.keyword=U,this.data=I.data,this.schema=I.schema[U],this.$data=C.$data&&I.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,h.schemaRefOrVal)(I,this.schema,U,this.$data),this.schemaType=C.schemaType,this.parentSchema=I.schema,this.params={},this.it=I,this.def=C,this.$data)this.schemaCode=I.gen.const("vSchema",Ge(this.$data,I));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,C.schemaType,C.allowUndefined))throw new Error(`${U} value must be ${JSON.stringify(C.schemaType)}`);("code"in C?C.trackErrors:C.errors!==!1)&&(this.errsCount=I.gen.const("_errs",l.default.errors))}result(I,C,U){this.failResult((0,s.not)(I),C,U)}failResult(I,C,U){this.gen.if(I),U?U():this.error(),C?(this.gen.else(),C(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(I,C){this.failResult((0,s.not)(I),void 0,C)}fail(I){if(I===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(I),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(I){if(!this.$data)return this.fail(I);let{schemaCode:C}=this;this.fail((0,s._)`${C} !== undefined && (${(0,s.or)(this.invalid$data(),I)})`)}error(I,C,U){if(C){this.setParams(C),this._error(I,U),this.setParams({});return}this._error(I,U)}_error(I,C){(I?z.reportExtraError:z.reportError)(this,this.def.error,C)}$dataError(){(0,z.reportError)(this,this.def.$dataError||z.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,z.resetErrorsCount)(this.gen,this.errsCount)}ok(I){this.allErrors||this.gen.if(I)}setParams(I,C){C?Object.assign(this.params,I):this.params=I}block$data(I,C,U=s.nil){this.gen.block(()=>{this.check$data(I,U),C()})}check$data(I=s.nil,C=s.nil){if(!this.$data)return;let{gen:U,schemaCode:oe,schemaType:ie,def:me}=this;U.if((0,s.or)((0,s._)`${oe} === undefined`,C)),I!==s.nil&&U.assign(I,!0),(ie.length||me.validateSchema)&&(U.elseIf(this.invalid$data()),this.$dataError(),I!==s.nil&&U.assign(I,!1)),U.else()}invalid$data(){let{gen:I,schemaCode:C,schemaType:U,def:oe,it:ie}=this;return(0,s.or)(me(),Ne());function me(){if(U.length){if(!(C instanceof s.Name))throw new Error("ajv implementation error");let qe=Array.isArray(U)?U:[U];return(0,s._)`${(0,o.checkDataTypes)(qe,C,ie.opts.strictNumbers,o.DataType.Wrong)}`}return s.nil}function Ne(){if(oe.validateSchema){let qe=I.scopeValue("validate$data",{ref:oe.validateSchema});return(0,s._)`!${qe}(${C})`}return s.nil}}subschema(I,C){let U=(0,c.getSubschema)(this.it,I);(0,c.extendSubschemaData)(U,this.it,I),(0,c.extendSubschemaMode)(U,I);let oe={...this.it,...U,items:void 0,props:void 0};return S(oe,C),oe}mergeEvaluated(I,C){let{it:U,gen:oe}=this;U.opts.unevaluated&&(U.props!==!0&&I.props!==void 0&&(U.props=h.mergeEvaluated.props(oe,I.props,U.props,C)),U.items!==!0&&I.items!==void 0&&(U.items=h.mergeEvaluated.items(oe,I.items,U.items,C)))}mergeValidEvaluated(I,C){let{it:U,gen:oe}=this;if(U.opts.unevaluated&&(U.props!==!0||U.items!==!0))return oe.if(C,()=>this.mergeEvaluated(I,s.Name)),!0}};e.KeywordCxt=te;function pe(I,C,U,oe){let ie=new te(I,U,C);"code"in U?U.code(ie,oe):ie.$data&&U.validate?(0,a.funcKeywordCode)(ie,U):"macro"in U?(0,a.macroKeywordCode)(ie,U):(U.compile||U.validate)&&(0,a.funcKeywordCode)(ie,U)}let ae=/^\/(?:[^~]|~0|~1)*$/,Re=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ge(I,{dataLevel:C,dataNames:U,dataPathArr:oe}){let ie,me;if(I==="")return l.default.rootData;if(I[0]==="/"){if(!ae.test(I))throw new Error(`Invalid JSON-pointer: ${I}`);ie=I,me=l.default.rootData}else{let Ae=Re.exec(I);if(!Ae)throw new Error(`Invalid JSON-pointer: ${I}`);let Ie=+Ae[1];if(ie=Ae[2],ie==="#"){if(Ie>=C)throw new Error(Fe("property/index",Ie));return oe[C-Ie]}if(Ie>C)throw new Error(Fe("data",Ie));if(me=U[C-Ie],!ie)return me}let Ne=me,qe=ie.split("/");for(let Ae of qe)Ae&&(me=(0,s._)`${me}${(0,s.getProperty)((0,h.unescapeJsonPointer)(Ae))}`,Ne=(0,s._)`${Ne} && ${me}`);return Ne;function Fe(Ae,Ie){return`Cannot access ${Ae} ${Ie} levels up, current level is ${C}`}}e.getData=Ge})),Ro=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}};e.default=t})),Qr=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=cs();var r=class extends Error{constructor(n,o,i,a){super(a||`can't resolve reference ${i} from id ${o}`),this.missingRef=(0,t.resolveUrl)(n,o,i),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}};e.default=r})),us=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=de(),r=Ro(),n=dt(),o=cs(),i=_e(),a=Xr();var c=class{constructor(d){var _;this.refs={},this.dynamicAnchors={};let p;typeof d.schema=="object"&&(p=d.schema),this.schema=d.schema,this.schemaId=d.schemaId,this.root=d.root||this,this.baseId=(_=d.baseId)!==null&&_!==void 0?_:(0,o.normalizeId)(p?.[d.schemaId||"$id"]),this.schemaPath=d.schemaPath,this.localRefs=d.localRefs,this.meta=d.meta,this.$async=p?.$async,this.refs={}}};e.SchemaEnv=c;function s(d){let _=h.call(this,d);if(_)return _;let p=(0,o.getFullPath)(this.opts.uriResolver,d.root.baseId),{es5:S,lines:w}=this.opts.code,{ownProperties:y}=this.opts,f=new t.CodeGen(this.scope,{es5:S,lines:w,ownProperties:y}),T;d.$async&&(T=f.scopeValue("Error",{ref:r.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let A=f.scopeName("validate");d.validateName=A;let F={gen:f,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue("schema",this.opts.code.source===!0?{ref:d.schema,code:(0,t.stringify)(d.schema)}:{ref:d.schema}),validateName:A,ValidationError:T,schema:d.schema,schemaEnv:d,rootId:p,baseId:d.baseId||p,schemaPath:t.nil,errSchemaPath:d.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this},M;try{this._compilations.add(d),(0,a.validateFunctionCode)(F),f.optimize(this.opts.code.optimize);let D=f.toString();M=`${f.scopeRefs(n.default.scope)}return ${D}`,this.opts.code.process&&(M=this.opts.code.process(M,d));let Y=new Function(`${n.default.self}`,`${n.default.scope}`,M)(this,this.scope.get());if(this.scope.value(A,{ref:Y}),Y.errors=null,Y.schema=d.schema,Y.schemaEnv=d,d.$async&&(Y.$async=!0),this.opts.code.source===!0&&(Y.source={validateName:A,validateCode:D,scopeValues:f._values}),this.opts.unevaluated){let{props:K,items:fe}=F;Y.evaluated={props:K instanceof t.Name?void 0:K,items:fe instanceof t.Name?void 0:fe,dynamicProps:K instanceof t.Name,dynamicItems:fe instanceof t.Name},Y.source&&(Y.source.evaluated=(0,t.stringify)(Y.evaluated))}return d.validate=Y,d}catch(D){throw delete d.validate,delete d.validateName,M&&this.logger.error("Error compiling schema, function code:",M),D}finally{this._compilations.delete(d)}}e.compileSchema=s;function l(d,_,p){var S;p=(0,o.resolveUrl)(this.opts.uriResolver,_,p);let w=d.refs[p];if(w)return w;let y=R.call(this,d,p);if(y===void 0){let f=(S=d.localRefs)===null||S===void 0?void 0:S[p],{schemaId:T}=this.opts;f&&(y=new c({schema:f,schemaId:T,root:d,baseId:_}))}if(y!==void 0)return d.refs[p]=m.call(this,y)}e.resolveRef=l;function m(d){return(0,o.inlineRef)(d.schema,this.opts.inlineRefs)?d.schema:d.validate?d:s.call(this,d)}function h(d){for(let _ of this._compilations)if(z(_,d))return _}e.getCompilingSchema=h;function z(d,_){return d.schema===_.schema&&d.root===_.root&&d.baseId===_.baseId}function R(d,_){let p;for(;typeof(p=this.refs[_])=="string";)_=p;return p||this.schemas[_]||v.call(this,d,_)}function v(d,_){let p=this.opts.uriResolver.parse(_),S=(0,o._getFullPath)(this.opts.uriResolver,p),w=(0,o.getFullPath)(this.opts.uriResolver,d.baseId,void 0);if(Object.keys(d.schema).length>0&&S===w)return g.call(this,p,d);let y=(0,o.normalizeId)(S),f=this.refs[y]||this.schemas[y];if(typeof f=="string"){let T=v.call(this,d,f);return typeof T?.schema!="object"?void 0:g.call(this,p,T)}if(typeof f?.schema=="object"){if(f.validate||s.call(this,f),y===(0,o.normalizeId)(_)){let{schema:T}=f,{schemaId:A}=this.opts,F=T[A];return F&&(w=(0,o.resolveUrl)(this.opts.uriResolver,w,F)),new c({schema:T,schemaId:A,root:d,baseId:w})}return g.call(this,p,f)}}e.resolveSchema=v;let b=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function g(d,{baseId:_,schema:p,root:S}){var w;if(((w=d.fragment)===null||w===void 0?void 0:w[0])!=="/")return;for(let T of d.fragment.slice(1).split("/")){if(typeof p=="boolean")return;let A=p[(0,i.unescapeFragment)(T)];if(A===void 0)return;p=A;let F=typeof p=="object"&&p[this.opts.schemaId];!b.has(T)&&F&&(_=(0,o.resolveUrl)(this.opts.uriResolver,_,F))}let y;if(typeof p!="boolean"&&p.$ref&&!(0,i.schemaHasRulesButRef)(p,this.RULES)){let T=(0,o.resolveUrl)(this.opts.uriResolver,_,p.$ref);y=v.call(this,S,T)}let{schemaId:f}=this.opts;if(y=y||new c({schema:p,schemaId:f,root:S,baseId:_}),y.schema!==y.root.schema)return y}})),JS=L(((e,t)=>{t.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}})),$h=L(((e,t)=>{let r=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),n=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function o(v){let b="",g=0,d=0;for(d=0;d=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";b+=v[d];break}for(d+=1;d=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";b+=v[d]}return b}let i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function a(v){return v.length=0,!0}function c(v,b,g){if(v.length){let d=o(v);if(d!=="")b.push(d);else return g.error=!0,!1;v.length=0}return!0}function s(v){let b=0,g={error:!1,address:"",zone:""},d=[],_=[],p=!1,S=!1,w=c;for(let y=0;y7){g.error=!0;break}y>0&&v[y-1]===":"&&(p=!0),d.push(":");continue}else if(f==="%"){if(!w(_,d,g))break;w=a}else{_.push(f);continue}}return _.length&&(w===a?g.zone=_.join(""):S?d.push(_.join("")):d.push(o(_))),g.address=d.join(""),g}function l(v){if(m(v,":")<2)return{host:v,isIPV6:!1};let b=s(v);if(b.error)return{host:v,isIPV6:!1};{let g=b.address,d=b.address;return b.zone&&(g+="%"+b.zone,d+="%25"+b.zone),{host:g,isIPV6:!0,escapedHost:d}}}function m(v,b){let g=0;for(let d=0;d{let{isUUID:r}=$h(),n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,o=["http","https","ws","wss","urn","urn:uuid"];function i(f){return o.indexOf(f)!==-1}function a(f){return f.secure===!0?!0:f.secure===!1?!1:f.scheme?f.scheme.length===3&&(f.scheme[0]==="w"||f.scheme[0]==="W")&&(f.scheme[1]==="s"||f.scheme[1]==="S")&&(f.scheme[2]==="s"||f.scheme[2]==="S"):!1}function c(f){return f.host||(f.error=f.error||"HTTP URIs must have a host."),f}function s(f){let T=String(f.scheme).toLowerCase()==="https";return(f.port===(T?443:80)||f.port==="")&&(f.port=void 0),f.path||(f.path="/"),f}function l(f){return f.secure=a(f),f.resourceName=(f.path||"/")+(f.query?"?"+f.query:""),f.path=void 0,f.query=void 0,f}function m(f){if((f.port===(a(f)?443:80)||f.port==="")&&(f.port=void 0),typeof f.secure=="boolean"&&(f.scheme=f.secure?"wss":"ws",f.secure=void 0),f.resourceName){let[T,A]=f.resourceName.split("?");f.path=T&&T!=="/"?T:void 0,f.query=A,f.resourceName=void 0}return f.fragment=void 0,f}function h(f,T){if(!f.path)return f.error="URN can not be parsed",f;let A=f.path.match(n);if(A){let F=T.scheme||f.scheme||"urn";f.nid=A[1].toLowerCase(),f.nss=A[2];let M=y(`${F}:${T.nid||f.nid}`);f.path=void 0,M&&(f=M.parse(f,T))}else f.error=f.error||"URN can not be parsed.";return f}function z(f,T){if(f.nid===void 0)throw new Error("URN without nid cannot be serialized");let A=T.scheme||f.scheme||"urn",F=f.nid.toLowerCase(),M=y(`${A}:${T.nid||F}`);M&&(f=M.serialize(f,T));let D=f,Y=f.nss;return D.path=`${F||T.nid}:${Y}`,T.skipEscape=!0,D}function R(f,T){let A=f;return A.uuid=A.nss,A.nss=void 0,!T.tolerant&&(!A.uuid||!r(A.uuid))&&(A.error=A.error||"UUID is not valid."),A}function v(f){let T=f;return T.nss=(f.uuid||"").toLowerCase(),T}let b={scheme:"http",domainHost:!0,parse:c,serialize:s},g={scheme:"https",domainHost:b.domainHost,parse:c,serialize:s},d={scheme:"ws",domainHost:!0,parse:l,serialize:m},_={scheme:"wss",domainHost:d.domainHost,parse:d.parse,serialize:d.serialize},w={http:b,https:g,ws:d,wss:_,urn:{scheme:"urn",parse:h,serialize:z,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:R,serialize:v,skipNormalize:!0}};Object.setPrototypeOf(w,null);function y(f){return f&&(w[f]||w[f.toLowerCase()])||void 0}t.exports={wsIsSecure:a,SCHEMES:w,isValidSchemeName:i,getSchemeHandler:y}})),KS=L(((e,t)=>{let{normalizeIPv6:r,removeDotSegments:n,recomposeAuthority:o,normalizeComponentEncoding:i,isIPv4:a,nonSimpleDomain:c}=$h(),{SCHEMES:s,getSchemeHandler:l}=BS();function m(_,p){return typeof _=="string"?_=v(g(_,p),p):typeof _=="object"&&(_=g(v(_,p),p)),_}function h(_,p,S){let w=S?Object.assign({scheme:"null"},S):{scheme:"null"},y=z(g(_,w),g(p,w),w,!0);return w.skipEscape=!0,v(y,w)}function z(_,p,S,w){let y={};return w||(_=g(v(_,S),S),p=g(v(p,S),S)),S=S||{},!S.tolerant&&p.scheme?(y.scheme=p.scheme,y.userinfo=p.userinfo,y.host=p.host,y.port=p.port,y.path=n(p.path||""),y.query=p.query):(p.userinfo!==void 0||p.host!==void 0||p.port!==void 0?(y.userinfo=p.userinfo,y.host=p.host,y.port=p.port,y.path=n(p.path||""),y.query=p.query):(p.path?(p.path[0]==="/"?y.path=n(p.path):((_.userinfo!==void 0||_.host!==void 0||_.port!==void 0)&&!_.path?y.path="/"+p.path:_.path?y.path=_.path.slice(0,_.path.lastIndexOf("/")+1)+p.path:y.path=p.path,y.path=n(y.path)),y.query=p.query):(y.path=_.path,p.query!==void 0?y.query=p.query:y.query=_.query),y.userinfo=_.userinfo,y.host=_.host,y.port=_.port),y.scheme=_.scheme),y.fragment=p.fragment,y}function R(_,p,S){return typeof _=="string"?(_=unescape(_),_=v(i(g(_,S),!0),{...S,skipEscape:!0})):typeof _=="object"&&(_=v(i(_,!0),{...S,skipEscape:!0})),typeof p=="string"?(p=unescape(p),p=v(i(g(p,S),!0),{...S,skipEscape:!0})):typeof p=="object"&&(p=v(i(p,!0),{...S,skipEscape:!0})),_.toLowerCase()===p.toLowerCase()}function v(_,p){let S={host:_.host,scheme:_.scheme,userinfo:_.userinfo,port:_.port,path:_.path,query:_.query,nid:_.nid,nss:_.nss,uuid:_.uuid,fragment:_.fragment,reference:_.reference,resourceName:_.resourceName,secure:_.secure,error:""},w=Object.assign({},p),y=[],f=l(w.scheme||S.scheme);f&&f.serialize&&f.serialize(S,w),S.path!==void 0&&(w.skipEscape?S.path=unescape(S.path):(S.path=escape(S.path),S.scheme!==void 0&&(S.path=S.path.split("%3A").join(":")))),w.reference!=="suffix"&&S.scheme&&y.push(S.scheme,":");let T=o(S);if(T!==void 0&&(w.reference!=="suffix"&&y.push("//"),y.push(T),S.path&&S.path[0]!=="/"&&y.push("/")),S.path!==void 0){let A=S.path;!w.absolutePath&&(!f||!f.absolutePath)&&(A=n(A)),T===void 0&&A[0]==="/"&&A[1]==="/"&&(A="/%2F"+A.slice(2)),y.push(A)}return S.query!==void 0&&y.push("?",S.query),S.fragment!==void 0&&y.push("#",S.fragment),y.join("")}let b=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(_,p){let S=Object.assign({},p),w={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},y=!1;S.reference==="suffix"&&(S.scheme?_=S.scheme+":"+_:_="//"+_);let f=_.match(b);if(f){if(w.scheme=f[1],w.userinfo=f[3],w.host=f[4],w.port=parseInt(f[5],10),w.path=f[6]||"",w.query=f[7],w.fragment=f[8],isNaN(w.port)&&(w.port=f[5]),w.host)if(a(w.host)===!1){let A=r(w.host);w.host=A.host.toLowerCase(),y=A.isIPV6}else y=!0;w.scheme===void 0&&w.userinfo===void 0&&w.host===void 0&&w.port===void 0&&w.query===void 0&&!w.path?w.reference="same-document":w.scheme===void 0?w.reference="relative":w.fragment===void 0?w.reference="absolute":w.reference="uri",S.reference&&S.reference!=="suffix"&&S.reference!==w.reference&&(w.error=w.error||"URI is not a "+S.reference+" reference.");let T=l(S.scheme||w.scheme);if(!S.unicodeSupport&&(!T||!T.unicodeSupport)&&w.host&&(S.domainHost||T&&T.domainHost)&&y===!1&&c(w.host))try{w.host=URL.domainToASCII(w.host.toLowerCase())}catch(A){w.error=w.error||"Host's domain name can not be converted to ASCII: "+A}(!T||T&&!T.skipNormalize)&&(_.indexOf("%")!==-1&&(w.scheme!==void 0&&(w.scheme=unescape(w.scheme)),w.host!==void 0&&(w.host=unescape(w.host))),w.path&&(w.path=escape(unescape(w.path))),w.fragment&&(w.fragment=encodeURI(decodeURIComponent(w.fragment)))),T&&T.parse&&T.parse(w,S)}else w.error=w.error||"URI can not be parsed.";return w}let d={SCHEMES:s,normalize:m,resolve:h,resolveComponent:z,equal:R,serialize:v,parse:g};t.exports=d,t.exports.default=d,t.exports.fastUri=d})),GS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=KS();t.code='require("ajv/dist/runtime/uri").default',e.default=t})),nl=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Xr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=de();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});let n=Ro(),o=Qr(),i=Sh(),a=us(),c=de(),s=cs(),l=as(),m=_e(),h=JS(),z=GS(),R=(k,x)=>new RegExp(k,x);R.code="new RegExp";let v=["removeAdditional","useDefaults","coerceTypes"],b=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},d={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function p(k){var x,V,$,P,N,H,te,pe,ae,Re,Ge,I,C,U,oe,ie,me,Ne,qe,Fe,Ae,Ie,nt,Ue,_t;let at=k.strict,St=(x=k.code)===null||x===void 0?void 0:x.optimize,Et=St===!0||St===void 0?1:St||0,It=($=(V=k.code)===null||V===void 0?void 0:V.regExp)!==null&&$!==void 0?$:R,Bt=(P=k.uriResolver)!==null&&P!==void 0?P:z.default;return{strictSchema:(H=(N=k.strictSchema)!==null&&N!==void 0?N:at)!==null&&H!==void 0?H:!0,strictNumbers:(pe=(te=k.strictNumbers)!==null&&te!==void 0?te:at)!==null&&pe!==void 0?pe:!0,strictTypes:(Re=(ae=k.strictTypes)!==null&&ae!==void 0?ae:at)!==null&&Re!==void 0?Re:"log",strictTuples:(I=(Ge=k.strictTuples)!==null&&Ge!==void 0?Ge:at)!==null&&I!==void 0?I:"log",strictRequired:(U=(C=k.strictRequired)!==null&&C!==void 0?C:at)!==null&&U!==void 0?U:!1,code:k.code?{...k.code,optimize:Et,regExp:It}:{optimize:Et,regExp:It},loopRequired:(oe=k.loopRequired)!==null&&oe!==void 0?oe:_,loopEnum:(ie=k.loopEnum)!==null&&ie!==void 0?ie:_,meta:(me=k.meta)!==null&&me!==void 0?me:!0,messages:(Ne=k.messages)!==null&&Ne!==void 0?Ne:!0,inlineRefs:(qe=k.inlineRefs)!==null&&qe!==void 0?qe:!0,schemaId:(Fe=k.schemaId)!==null&&Fe!==void 0?Fe:"$id",addUsedSchema:(Ae=k.addUsedSchema)!==null&&Ae!==void 0?Ae:!0,validateSchema:(Ie=k.validateSchema)!==null&&Ie!==void 0?Ie:!0,validateFormats:(nt=k.validateFormats)!==null&&nt!==void 0?nt:!0,unicodeRegExp:(Ue=k.unicodeRegExp)!==null&&Ue!==void 0?Ue:!0,int32range:(_t=k.int32range)!==null&&_t!==void 0?_t:!0,uriResolver:Bt}}var S=class{constructor(k={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,k=this.opts={...k,...p(k)};let{es5:x,lines:V}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:b,es5:x,lines:V}),this.logger=D(k.logger);let $=k.validateFormats;k.validateFormats=!1,this.RULES=(0,i.getRules)(),w.call(this,g,k,"NOT SUPPORTED"),w.call(this,d,k,"DEPRECATED","warn"),this._metaOpts=F.call(this),k.formats&&T.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),k.keywords&&A.call(this,k.keywords),typeof k.meta=="object"&&this.addMetaSchema(k.meta),f.call(this),k.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:k,meta:x,schemaId:V}=this.opts,$=h;V==="id"&&($={...h},$.id=$.$id,delete $.$id),x&&k&&this.addMetaSchema($,$[V],!1)}defaultMeta(){let{meta:k,schemaId:x}=this.opts;return this.opts.defaultMeta=typeof k=="object"?k[x]||k:void 0}validate(k,x){let V;if(typeof k=="string"){if(V=this.getSchema(k),!V)throw new Error(`no schema with key or ref "${k}"`)}else V=this.compile(k);let $=V(x);return"$async"in V||(this.errors=V.errors),$}compile(k,x){let V=this._addSchema(k,x);return V.validate||this._compileSchemaEnv(V)}compileAsync(k,x){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:V}=this.opts;return $.call(this,k,x);async function $(ae,Re){await P.call(this,ae.$schema);let Ge=this._addSchema(ae,Re);return Ge.validate||N.call(this,Ge)}async function P(ae){ae&&!this.getSchema(ae)&&await $.call(this,{$ref:ae},!0)}async function N(ae){try{return this._compileSchemaEnv(ae)}catch(Re){if(!(Re instanceof o.default))throw Re;return H.call(this,Re),await te.call(this,Re.missingSchema),N.call(this,ae)}}function H({missingSchema:ae,missingRef:Re}){if(this.refs[ae])throw new Error(`AnySchema ${ae} is loaded but ${Re} cannot be resolved`)}async function te(ae){let Re=await pe.call(this,ae);this.refs[ae]||await P.call(this,Re.$schema),this.refs[ae]||this.addSchema(Re,ae,x)}async function pe(ae){let Re=this._loading[ae];if(Re)return Re;try{return await(this._loading[ae]=V(ae))}finally{delete this._loading[ae]}}}addSchema(k,x,V,$=this.opts.validateSchema){if(Array.isArray(k)){for(let N of k)this.addSchema(N,void 0,V,$);return this}let P;if(typeof k=="object"){let{schemaId:N}=this.opts;if(P=k[N],P!==void 0&&typeof P!="string")throw new Error(`schema ${N} must be string`)}return x=(0,s.normalizeId)(x||P),this._checkUnique(x),this.schemas[x]=this._addSchema(k,V,x,$,!0),this}addMetaSchema(k,x,V=this.opts.validateSchema){return this.addSchema(k,x,!0,V),this}validateSchema(k,x){if(typeof k=="boolean")return!0;let V;if(V=k.$schema,V!==void 0&&typeof V!="string")throw new Error("$schema must be a string");if(V=V||this.opts.defaultMeta||this.defaultMeta(),!V)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let $=this.validate(V,k);if(!$&&x){let P="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(P);else throw new Error(P)}return $}getSchema(k){let x;for(;typeof(x=y.call(this,k))=="string";)k=x;if(x===void 0){let{schemaId:V}=this.opts,$=new a.SchemaEnv({schema:{},schemaId:V});if(x=a.resolveSchema.call(this,$,k),!x)return;this.refs[k]=x}return x.validate||this._compileSchemaEnv(x)}removeSchema(k){if(k instanceof RegExp)return this._removeAllSchemas(this.schemas,k),this._removeAllSchemas(this.refs,k),this;switch(typeof k){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let x=y.call(this,k);return typeof x=="object"&&this._cache.delete(x.schema),delete this.schemas[k],delete this.refs[k],this}case"object":{let x=k;this._cache.delete(x);let V=k[this.opts.schemaId];return V&&(V=(0,s.normalizeId)(V),delete this.schemas[V],delete this.refs[V]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(k){for(let x of k)this.addKeyword(x);return this}addKeyword(k,x){let V;if(typeof k=="string")V=k,typeof x=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),x.keyword=V);else if(typeof k=="object"&&x===void 0){if(x=k,V=x.keyword,Array.isArray(V)&&!V.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(K.call(this,V,x),!x)return(0,m.eachItem)(V,P=>fe.call(this,P)),this;ze.call(this,x);let $={...x,type:(0,l.getJSONTypes)(x.type),schemaType:(0,l.getJSONTypes)(x.schemaType)};return(0,m.eachItem)(V,$.type.length===0?P=>fe.call(this,P,$):P=>$.type.forEach(N=>fe.call(this,P,$,N))),this}getKeyword(k){let x=this.RULES.all[k];return typeof x=="object"?x.definition:!!x}removeKeyword(k){let{RULES:x}=this;delete x.keywords[k],delete x.all[k];for(let V of x.rules){let $=V.rules.findIndex(P=>P.keyword===k);$>=0&&V.rules.splice($,1)}return this}addFormat(k,x){return typeof x=="string"&&(x=new RegExp(x)),this.formats[k]=x,this}errorsText(k=this.errors,{separator:x=", ",dataVar:V="data"}={}){return!k||k.length===0?"No errors":k.map($=>`${V}${$.instancePath} ${$.message}`).reduce(($,P)=>$+x+P)}$dataMetaSchema(k,x){let V=this.RULES.all;k=JSON.parse(JSON.stringify(k));for(let $ of x){let P=$.split("/").slice(1),N=k;for(let H of P)N=N[H];for(let H in V){let te=V[H];if(typeof te!="object")continue;let{$data:pe}=te.definition,ae=N[H];pe&&ae&&(N[H]=ve(ae))}}return k}_removeAllSchemas(k,x){for(let V in k){let $=k[V];(!x||x.test(V))&&(typeof $=="string"?delete k[V]:$&&!$.meta&&(this._cache.delete($.schema),delete k[V]))}}_addSchema(k,x,V,$=this.opts.validateSchema,P=this.opts.addUsedSchema){let N,{schemaId:H}=this.opts;if(typeof k=="object")N=k[H];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof k!="boolean")throw new Error("schema must be object or boolean")}let te=this._cache.get(k);if(te!==void 0)return te;V=(0,s.normalizeId)(N||V);let pe=s.getSchemaRefs.call(this,k,V);return te=new a.SchemaEnv({schema:k,schemaId:H,meta:x,baseId:V,localRefs:pe}),this._cache.set(te.schema,te),P&&!V.startsWith("#")&&(V&&this._checkUnique(V),this.refs[V]=te),$&&this.validateSchema(k,!0),te}_checkUnique(k){if(this.schemas[k]||this.refs[k])throw new Error(`schema with key or id "${k}" already exists`)}_compileSchemaEnv(k){if(k.meta?this._compileMetaSchema(k):a.compileSchema.call(this,k),!k.validate)throw new Error("ajv implementation error");return k.validate}_compileMetaSchema(k){let x=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,k)}finally{this.opts=x}}};S.ValidationError=n.default,S.MissingRefError=o.default,e.default=S;function w(k,x,V,$="error"){for(let P in k){let N=P;N in x&&this.logger[$](`${V}: option ${P}. ${k[N]}`)}}function y(k){return k=(0,s.normalizeId)(k),this.schemas[k]||this.refs[k]}function f(){let k=this.opts.schemas;if(k)if(Array.isArray(k))this.addSchema(k);else for(let x in k)this.addSchema(k[x],x)}function T(){for(let k in this.opts.formats){let x=this.opts.formats[k];x&&this.addFormat(k,x)}}function A(k){if(Array.isArray(k)){this.addVocabulary(k);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let x in k){let V=k[x];V.keyword||(V.keyword=x),this.addKeyword(V)}}function F(){let k={...this.opts};for(let x of v)delete k[x];return k}let M={log(){},warn(){},error(){}};function D(k){if(k===!1)return M;if(k===void 0)return console;if(k.log&&k.warn&&k.error)return k;throw new Error("logger must implement log, warn and error methods")}let Y=/^[a-z_$][a-z0-9_$:-]*$/i;function K(k,x){let{RULES:V}=this;if((0,m.eachItem)(k,$=>{if(V.keywords[$])throw new Error(`Keyword ${$} is already defined`);if(!Y.test($))throw new Error(`Keyword ${$} has invalid name`)}),!!x&&x.$data&&!("code"in x||"validate"in x))throw new Error('$data keyword must have "code" or "validate" function')}function fe(k,x,V){var $;let P=x?.post;if(V&&P)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:N}=this,H=P?N.post:N.rules.find(({type:pe})=>pe===V);if(H||(H={type:V,rules:[]},N.rules.push(H)),N.keywords[k]=!0,!x)return;let te={keyword:k,definition:{...x,type:(0,l.getJSONTypes)(x.type),schemaType:(0,l.getJSONTypes)(x.schemaType)}};x.before?Te.call(this,H,te,x.before):H.rules.push(te),N.all[k]=te,($=x.implements)===null||$===void 0||$.forEach(pe=>this.addKeyword(pe))}function Te(k,x,V){let $=k.rules.findIndex(P=>P.keyword===V);$>=0?k.rules.splice($,0,x):(k.rules.push(x),this.logger.warn(`rule ${V} is not defined`))}function ze(k){let{metaSchema:x}=k;x!==void 0&&(k.$data&&this.opts.$data&&(x=ve(x)),k.validateSchema=this.compile(x,!0))}let Ce={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ve(k){return{anyOf:[k,Ce]}}})),WS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};e.default=t})),ol=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Qr(),r=mt(),n=de(),o=dt(),i=us(),a=_e(),c={keyword:"$ref",schemaType:"string",code(m){let{gen:h,schema:z,it:R}=m,{baseId:v,schemaEnv:b,validateName:g,opts:d,self:_}=R,{root:p}=b;if((z==="#"||z==="#/")&&v===p.baseId)return w();let S=i.resolveRef.call(_,p,v,z);if(S===void 0)throw new t.default(R.opts.uriResolver,v,z);if(S instanceof i.SchemaEnv)return y(S);return f(S);function w(){if(b===p)return l(m,g,b,b.$async);let T=h.scopeValue("root",{ref:p});return l(m,(0,n._)`${T}.validate`,p,p.$async)}function y(T){l(m,s(m,T),T,T.$async)}function f(T){let A=h.scopeValue("schema",d.code.source===!0?{ref:T,code:(0,n.stringify)(T)}:{ref:T}),F=h.name("valid"),M=m.subschema({schema:T,dataTypes:[],schemaPath:n.nil,topSchemaRef:A,errSchemaPath:z},F);m.mergeEvaluated(M),m.ok(F)}}};function s(m,h){let{gen:z}=m;return h.validate?z.scopeValue("validate",{ref:h.validate}):(0,n._)`${z.scopeValue("wrapper",{ref:h})}.validate`}e.getValidate=s;function l(m,h,z,R){let{gen:v,it:b}=m,{allErrors:g,schemaEnv:d,opts:_}=b,p=_.passContext?o.default.this:n.nil;R?S():w();function S(){if(!d.$async)throw new Error("async schema referenced by sync schema");let T=v.let("valid");v.try(()=>{v.code((0,n._)`await ${(0,r.callValidateCode)(m,h,p)}`),f(h),g||v.assign(T,!0)},A=>{v.if((0,n._)`!(${A} instanceof ${b.ValidationError})`,()=>v.throw(A)),y(A),g||v.assign(T,!1)}),m.ok(T)}function w(){m.result((0,r.callValidateCode)(m,h,p),()=>f(h),()=>y(h))}function y(T){let A=(0,n._)`${T}.errors`;v.assign(o.default.vErrors,(0,n._)`${o.default.vErrors} === null ? ${A} : ${o.default.vErrors}.concat(${A})`),v.assign(o.default.errors,(0,n._)`${o.default.vErrors}.length`)}function f(T){var A;if(!b.opts.unevaluated)return;let F=(A=z?.validate)===null||A===void 0?void 0:A.evaluated;if(b.props!==!0)if(F&&!F.dynamicProps)F.props!==void 0&&(b.props=a.mergeEvaluated.props(v,F.props,b.props));else{let M=v.var("props",(0,n._)`${T}.evaluated.props`);b.props=a.mergeEvaluated.props(v,M,b.props,n.Name)}if(b.items!==!0)if(F&&!F.dynamicItems)F.items!==void 0&&(b.items=a.mergeEvaluated.items(v,F.items,b.items));else{let M=v.var("items",(0,n._)`${T}.evaluated.items`);b.items=a.mergeEvaluated.items(v,M,b.items,n.Name)}}}e.callRef=l,e.default=c})),zh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=WS(),r=ol(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,r.default];e.default=n})),YS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=t.operators,n={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:i,schemaCode:a})=>(0,t.str)`must be ${n[i].okStr} ${a}`,params:({keyword:i,schemaCode:a})=>(0,t._)`{comparison: ${n[i].okStr}, limit: ${a}}`},code(i){let{keyword:a,data:c,schemaCode:s}=i;i.fail$data((0,t._)`${c} ${n[a].fail} ${s} || isNaN(${c})`)}};e.default=o})),XS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){let{gen:o,data:i,schemaCode:a,it:c}=n,s=c.opts.multipleOfPrecision,l=o.let("res"),m=s?(0,t._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${s}`:(0,t._)`${l} !== parseInt(${l})`;n.fail$data((0,t._)`(${a} === 0 || (${l} = ${i}/${a}, ${m}))`)}};e.default=r})),QS=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(r){let n=r.length,o=0,i=0,a;for(;i=55296&&a<=56319&&i{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n=QS(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:i,schemaCode:a}){let c=i==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${c} than ${a} characters`},params:({schemaCode:i})=>(0,t._)`{limit: ${i}}`},code(i){let{keyword:a,data:c,schemaCode:s,it:l}=i,m=a==="maxLength"?t.operators.GT:t.operators.LT,h=l.opts.unicode===!1?(0,t._)`${c}.length`:(0,t._)`${(0,r.useFunc)(i.gen,n.default)}(${c})`;i.fail$data((0,t._)`${h} ${m} ${s}`)}};e.default=o})),ty=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mt(),r=_e(),n=de(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:i})=>(0,n.str)`must match pattern "${i}"`,params:({schemaCode:i})=>(0,n._)`{pattern: ${i}}`},code(i){let{gen:a,data:c,$data:s,schema:l,schemaCode:m,it:h}=i,z=h.opts.unicodeRegExp?"u":"";if(s){let{regExp:R}=h.opts.code,v=R.code==="new RegExp"?(0,n._)`new RegExp`:(0,r.useFunc)(a,R),b=a.let("valid");a.try(()=>a.assign(b,(0,n._)`${v}(${m}, ${z}).test(${c})`),()=>a.assign(b,!1)),i.fail$data((0,n._)`!${b}`)}else{let R=(0,t.usePattern)(i,l);i.fail$data((0,n._)`!${R}.test(${c})`)}}};e.default=o})),ry=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let i=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${o} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:i,schemaCode:a}=n,c=o==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${i}).length ${c} ${a}`)}};e.default=r})),ny=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mt(),r=de(),n=_e(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:i}})=>(0,r.str)`must have required property '${i}'`,params:({params:{missingProperty:i}})=>(0,r._)`{missingProperty: ${i}}`},code(i){let{gen:a,schema:c,schemaCode:s,data:l,$data:m,it:h}=i,{opts:z}=h;if(!m&&c.length===0)return;let R=c.length>=z.loopRequired;if(h.allErrors?v():b(),z.strictRequired){let _=i.parentSchema.properties,{definedProperties:p}=i.it;for(let S of c)if(_?.[S]===void 0&&!p.has(S)){let w=`required property "${S}" is not defined at "${h.schemaEnv.baseId+h.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(h,w,h.opts.strictRequired)}}function v(){if(R||m)i.block$data(r.nil,g);else for(let _ of c)(0,t.checkReportMissingProp)(i,_)}function b(){let _=a.let("missing");if(R||m){let p=a.let("valid",!0);i.block$data(p,()=>d(_,p)),i.ok(p)}else a.if((0,t.checkMissingProp)(i,c,_)),(0,t.reportMissingProp)(i,_),a.else()}function g(){a.forOf("prop",s,_=>{i.setParams({missingProperty:_}),a.if((0,t.noPropertyInData)(a,l,_,z.ownProperties),()=>i.error())})}function d(_,p){i.setParams({missingProperty:_}),a.forOf(_,s,()=>{a.assign(p,(0,t.propertyInData)(a,l,_,z.ownProperties)),a.if((0,r.not)(p),()=>{i.error(),a.break()})},r.nil)}}};e.default=o})),oy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let i=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${o} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:i,schemaCode:a}=n,c=o==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${i}.length ${c} ${a}`)}};e.default=r})),il=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=bh();t.code='require("ajv/dist/runtime/equal").default',e.default=t})),iy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=as(),r=de(),n=_e(),o=il(),i={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:c}})=>(0,r.str)`must NOT have duplicate items (items ## ${c} and ${a} are identical)`,params:({params:{i:a,j:c}})=>(0,r._)`{i: ${a}, j: ${c}}`},code(a){let{gen:c,data:s,$data:l,schema:m,parentSchema:h,schemaCode:z,it:R}=a;if(!l&&!m)return;let v=c.let("valid"),b=h.items?(0,t.getSchemaTypes)(h.items):[];a.block$data(v,g,(0,r._)`${z} === false`),a.ok(v);function g(){let S=c.let("i",(0,r._)`${s}.length`),w=c.let("j");a.setParams({i:S,j:w}),c.assign(v,!0),c.if((0,r._)`${S} > 1`,()=>(d()?_:p)(S,w))}function d(){return b.length>0&&!b.some(S=>S==="object"||S==="array")}function _(S,w){let y=c.name("item"),f=(0,t.checkDataTypes)(b,y,R.opts.strictNumbers,t.DataType.Wrong),T=c.const("indices",(0,r._)`{}`);c.for((0,r._)`;${S}--;`,()=>{c.let(y,(0,r._)`${s}[${S}]`),c.if(f,(0,r._)`continue`),b.length>1&&c.if((0,r._)`typeof ${y} == "string"`,(0,r._)`${y} += "_"`),c.if((0,r._)`typeof ${T}[${y}] == "number"`,()=>{c.assign(w,(0,r._)`${T}[${y}]`),a.error(),c.assign(v,!1).break()}).code((0,r._)`${T}[${y}] = ${S}`)})}function p(S,w){let y=(0,n.useFunc)(c,o.default),f=c.name("outer");c.label(f).for((0,r._)`;${S}--;`,()=>c.for((0,r._)`${w} = ${S}; ${w}--;`,()=>c.if((0,r._)`${y}(${s}[${S}], ${s}[${w}])`,()=>{a.error(),c.assign(v,!1).break(f)})))}}};e.default=i})),ay=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n=il(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:i})=>(0,t._)`{allowedValue: ${i}}`},code(i){let{gen:a,data:c,$data:s,schemaCode:l,schema:m}=i;s||m&&typeof m=="object"?i.fail$data((0,t._)`!${(0,r.useFunc)(a,n.default)}(${c}, ${l})`):i.fail((0,t._)`${m} !== ${c}`)}};e.default=o})),sy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n=il(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:i})=>(0,t._)`{allowedValues: ${i}}`},code(i){let{gen:a,data:c,$data:s,schema:l,schemaCode:m,it:h}=i;if(!s&&l.length===0)throw new Error("enum must have non-empty array");let z=l.length>=h.opts.loopEnum,R,v=()=>R??(R=(0,r.useFunc)(a,n.default)),b;if(z||s)b=a.let("valid"),i.block$data(b,g);else{if(!Array.isArray(l))throw new Error("ajv implementation error");let _=a.const("vSchema",m);b=(0,t.or)(...l.map((p,S)=>d(_,S)))}i.pass(b);function g(){a.assign(b,!1),a.forOf("v",m,_=>a.if((0,t._)`${v()}(${c}, ${_})`,()=>a.assign(b,!0).break()))}function d(_,p){let S=l[p];return typeof S=="object"&&S!==null?(0,t._)`${v()}(${c}, ${_}[${p}])`:(0,t._)`${c} === ${S}`}}};e.default=o})),Rh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=YS(),r=XS(),n=ey(),o=ty(),i=ry(),a=ny(),c=oy(),s=iy(),l=ay(),m=sy(),h=[t.default,r.default,n.default,o.default,i.default,a.default,c.default,s.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,m.default];e.default=h})),wh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=de(),r=_e(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,t.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,t._)`{limit: ${i}}`},code(i){let{parentSchema:a,it:c}=i,{items:s}=a;if(!Array.isArray(s)){(0,r.checkStrictMode)(c,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(i,s)}};function o(i,a){let{gen:c,schema:s,data:l,keyword:m,it:h}=i;h.items=!0;let z=c.const("len",(0,t._)`${l}.length`);if(s===!1)i.setParams({len:a.length}),i.pass((0,t._)`${z} <= ${a.length}`);else if(typeof s=="object"&&!(0,r.alwaysValidSchema)(h,s)){let v=c.var("valid",(0,t._)`${z} <= ${a.length}`);c.if((0,t.not)(v),()=>R(v)),i.ok(v)}function R(v){c.forRange("i",a.length,z,b=>{i.subschema({keyword:m,dataProp:b,dataPropType:r.Type.Num},v),h.allErrors||c.if((0,t.not)(v),()=>c.break())})}}e.validateAdditionalItems=o,e.default=n})),Th=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=de(),r=_e(),n=mt(),o={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){let{schema:c,it:s}=a;if(Array.isArray(c))return i(a,"additionalItems",c);s.items=!0,!(0,r.alwaysValidSchema)(s,c)&&a.ok((0,n.validateArray)(a))}};function i(a,c,s=a.schema){let{gen:l,parentSchema:m,data:h,keyword:z,it:R}=a;g(m),R.opts.unevaluated&&s.length&&R.items!==!0&&(R.items=r.mergeEvaluated.items(l,s.length,R.items));let v=l.name("valid"),b=l.const("len",(0,t._)`${h}.length`);s.forEach((d,_)=>{(0,r.alwaysValidSchema)(R,d)||(l.if((0,t._)`${b} > ${_}`,()=>a.subschema({keyword:z,schemaProp:_,dataProp:_},v)),a.ok(v))});function g(d){let{opts:_,errSchemaPath:p}=R,S=s.length,w=S===d.minItems&&(S===d.maxItems||d[c]===!1);if(_.strictTuples&&!w){let y=`"${z}" is ${S}-tuple, but minItems or maxItems/${c} are not specified or different at path "${p}"`;(0,r.checkStrictMode)(R,y,_.strictTuples)}}}e.validateTuple=i,e.default=o})),cy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Th(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,t.validateTuple)(n,"items")};e.default=r})),uy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n=mt(),o=wh(),i={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){let{schema:c,parentSchema:s,it:l}=a,{prefixItems:m}=s;l.items=!0,!(0,r.alwaysValidSchema)(l,c)&&(m?(0,o.validateAdditionalItems)(a,m):a.ok((0,n.validateArray)(a)))}};e.default=i})),ly=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:i}})=>i===void 0?(0,t.str)`must contain at least ${o} valid item(s)`:(0,t.str)`must contain at least ${o} and no more than ${i} valid item(s)`,params:({params:{min:o,max:i}})=>i===void 0?(0,t._)`{minContains: ${o}}`:(0,t._)`{minContains: ${o}, maxContains: ${i}}`},code(o){let{gen:i,schema:a,parentSchema:c,data:s,it:l}=o,m,h,{minContains:z,maxContains:R}=c;l.opts.next?(m=z===void 0?1:z,h=R):m=1;let v=i.const("len",(0,t._)`${s}.length`);if(o.setParams({min:m,max:h}),h===void 0&&m===0){(0,r.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(h!==void 0&&m>h){(0,r.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,r.alwaysValidSchema)(l,a)){let p=(0,t._)`${v} >= ${m}`;h!==void 0&&(p=(0,t._)`${p} && ${v} <= ${h}`),o.pass(p);return}l.items=!0;let b=i.name("valid");h===void 0&&m===1?d(b,()=>i.if(b,()=>i.break())):m===0?(i.let(b,!0),h!==void 0&&i.if((0,t._)`${s}.length > 0`,g)):(i.let(b,!1),g()),o.result(b,()=>o.reset());function g(){let p=i.name("_valid"),S=i.let("count",0);d(p,()=>i.if(p,()=>_(S)))}function d(p,S){i.forRange("i",0,v,w=>{o.subschema({keyword:"contains",dataProp:w,dataPropType:r.Type.Num,compositeRule:!0},p),S()})}function _(p){i.code((0,t._)`${p}++`),h===void 0?i.if((0,t._)`${p} >= ${m}`,()=>i.assign(b,!0).break()):(i.if((0,t._)`${p} > ${h}`,()=>i.assign(b,!1).break()),m===1?i.assign(b,!0):i.if((0,t._)`${p} >= ${m}`,()=>i.assign(b,!0)))}}};e.default=n})),al=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=de(),r=_e(),n=mt();e.error={message:({params:{property:s,depsCount:l,deps:m}})=>{let h=l===1?"property":"properties";return(0,t.str)`must have ${h} ${m} when property ${s} is present`},params:({params:{property:s,depsCount:l,deps:m,missingProperty:h}})=>(0,t._)`{property: ${s}, + missingProperty: ${h}, + depsCount: ${l}, + deps: ${m}}`};let o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(s){let[l,m]=i(s);a(s,l),c(s,m)}};function i({schema:s}){let l={},m={};for(let h in s){if(h==="__proto__")continue;let z=Array.isArray(s[h])?l:m;z[h]=s[h]}return[l,m]}function a(s,l=s.schema){let{gen:m,data:h,it:z}=s;if(Object.keys(l).length===0)return;let R=m.let("missing");for(let v in l){let b=l[v];if(b.length===0)continue;let g=(0,n.propertyInData)(m,h,v,z.opts.ownProperties);s.setParams({property:v,depsCount:b.length,deps:b.join(", ")}),z.allErrors?m.if(g,()=>{for(let d of b)(0,n.checkReportMissingProp)(s,d)}):(m.if((0,t._)`${g} && (${(0,n.checkMissingProp)(s,b,R)})`),(0,n.reportMissingProp)(s,R),m.else())}}e.validatePropertyDeps=a;function c(s,l=s.schema){let{gen:m,data:h,keyword:z,it:R}=s,v=m.name("valid");for(let b in l)(0,r.alwaysValidSchema)(R,l[b])||(m.if((0,n.propertyInData)(m,h,b,R.opts.ownProperties),()=>{let g=s.subschema({keyword:z,schemaProp:b},v);s.mergeValidEvaluated(g,v)},()=>m.var(v,!0)),s.ok(v))}e.validateSchemaDeps=c,e.default=o})),dy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,t._)`{propertyName: ${o.propertyName}}`},code(o){let{gen:i,schema:a,data:c,it:s}=o;if((0,r.alwaysValidSchema)(s,a))return;let l=i.name("valid");i.forIn("key",c,m=>{o.setParams({propertyName:m}),o.subschema({keyword:"propertyNames",data:m,dataTypes:["string"],propertyName:m,compositeRule:!0},l),i.if((0,t.not)(l),()=>{o.error(!0),s.allErrors||i.break()})}),o.ok(l)}};e.default=n})),Eh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mt(),r=de(),n=dt(),o=_e(),i={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,r._)`{additionalProperty: ${a.additionalProperty}}`},code(a){let{gen:c,schema:s,parentSchema:l,data:m,errsCount:h,it:z}=a;if(!h)throw new Error("ajv implementation error");let{allErrors:R,opts:v}=z;if(z.props=!0,v.removeAdditional!=="all"&&(0,o.alwaysValidSchema)(z,s))return;let b=(0,t.allSchemaProperties)(l.properties),g=(0,t.allSchemaProperties)(l.patternProperties);d(),a.ok((0,r._)`${h} === ${n.default.errors}`);function d(){c.forIn("key",m,y=>{!b.length&&!g.length?S(y):c.if(_(y),()=>S(y))})}function _(y){let f;if(b.length>8){let T=(0,o.schemaRefOrVal)(z,l.properties,"properties");f=(0,t.isOwnProperty)(c,T,y)}else b.length?f=(0,r.or)(...b.map(T=>(0,r._)`${y} === ${T}`)):f=r.nil;return g.length&&(f=(0,r.or)(f,...g.map(T=>(0,r._)`${(0,t.usePattern)(a,T)}.test(${y})`))),(0,r.not)(f)}function p(y){c.code((0,r._)`delete ${m}[${y}]`)}function S(y){if(v.removeAdditional==="all"||v.removeAdditional&&s===!1){p(y);return}if(s===!1){a.setParams({additionalProperty:y}),a.error(),R||c.break();return}if(typeof s=="object"&&!(0,o.alwaysValidSchema)(z,s)){let f=c.name("valid");v.removeAdditional==="failing"?(w(y,f,!1),c.if((0,r.not)(f),()=>{a.reset(),p(y)})):(w(y,f),R||c.if((0,r.not)(f),()=>c.break()))}}function w(y,f,T){let A={keyword:"additionalProperties",dataProp:y,dataPropType:o.Type.Str};T===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(A,f)}}};e.default=i})),my=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xr(),r=mt(),n=_e(),o=Eh(),i={keyword:"properties",type:"object",schemaType:"object",code(a){let{gen:c,schema:s,parentSchema:l,data:m,it:h}=a;h.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&o.default.code(new t.KeywordCxt(h,o.default,"additionalProperties"));let z=(0,r.allSchemaProperties)(s);for(let d of z)h.definedProperties.add(d);h.opts.unevaluated&&z.length&&h.props!==!0&&(h.props=n.mergeEvaluated.props(c,(0,n.toHash)(z),h.props));let R=z.filter(d=>!(0,n.alwaysValidSchema)(h,s[d]));if(R.length===0)return;let v=c.name("valid");for(let d of R)b(d)?g(d):(c.if((0,r.propertyInData)(c,m,d,h.opts.ownProperties)),g(d),h.allErrors||c.else().var(v,!0),c.endIf()),a.it.definedProperties.add(d),a.ok(v);function b(d){return h.opts.useDefaults&&!h.compositeRule&&s[d].default!==void 0}function g(d){a.subschema({keyword:"properties",schemaProp:d,dataProp:d},v)}}};e.default=i})),py=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mt(),r=de(),n=_e(),o=_e(),i={keyword:"patternProperties",type:"object",schemaType:"object",code(a){let{gen:c,schema:s,data:l,parentSchema:m,it:h}=a,{opts:z}=h,R=(0,t.allSchemaProperties)(s),v=R.filter(w=>(0,n.alwaysValidSchema)(h,s[w]));if(R.length===0||v.length===R.length&&(!h.opts.unevaluated||h.props===!0))return;let b=z.strictSchema&&!z.allowMatchingProperties&&m.properties,g=c.name("valid");h.props!==!0&&!(h.props instanceof r.Name)&&(h.props=(0,o.evaluatedPropsToName)(c,h.props));let{props:d}=h;_();function _(){for(let w of R)b&&p(w),h.allErrors?S(w):(c.var(g,!0),S(w),c.if(g))}function p(w){for(let y in b)new RegExp(w).test(y)&&(0,n.checkStrictMode)(h,`property ${y} matches pattern ${w} (use allowMatchingProperties)`)}function S(w){c.forIn("key",l,y=>{c.if((0,r._)`${(0,t.usePattern)(a,w)}.test(${y})`,()=>{let f=v.includes(w);f||a.subschema({keyword:"patternProperties",schemaProp:w,dataProp:y,dataPropType:o.Type.Str},g),h.opts.unevaluated&&d!==!0?c.assign((0,r._)`${d}[${y}]`,!0):!f&&!h.allErrors&&c.if((0,r.not)(g),()=>c.break())})})}}};e.default=i})),fy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_e(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:o,schema:i,it:a}=n;if((0,t.alwaysValidSchema)(a,i)){n.fail();return}let c=o.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},c),n.failResult(c,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};e.default=r})),hy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:mt().validateUnion,error:{message:"must match a schema in anyOf"}};e.default=t})),gy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,t._)`{passingSchemas: ${o.passing}}`},code(o){let{gen:i,schema:a,parentSchema:c,it:s}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(s.opts.discriminator&&c.discriminator)return;let l=a,m=i.let("valid",!1),h=i.let("passing",null),z=i.name("_valid");o.setParams({passing:h}),i.block(R),o.result(m,()=>o.reset(),()=>o.error(!0));function R(){l.forEach((v,b)=>{let g;(0,r.alwaysValidSchema)(s,v)?i.var(z,!0):g=o.subschema({keyword:"oneOf",schemaProp:b,compositeRule:!0},z),b>0&&i.if((0,t._)`${z} && ${m}`).assign(m,!1).assign(h,(0,t._)`[${h}, ${b}]`).else(),i.if(z,()=>{i.assign(m,!0),i.assign(h,b),g&&o.mergeEvaluated(g,t.Name)})})}}};e.default=n})),vy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_e(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:o,schema:i,it:a}=n;if(!Array.isArray(i))throw new Error("ajv implementation error");let c=o.name("valid");i.forEach((s,l)=>{if((0,t.alwaysValidSchema)(a,s))return;let m=n.subschema({keyword:"allOf",schemaProp:l},c);n.ok(c),n.mergeEvaluated(m)})}};e.default=r})),_y=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:i})=>(0,t.str)`must match "${i.ifClause}" schema`,params:({params:i})=>(0,t._)`{failingKeyword: ${i.ifClause}}`},code(i){let{gen:a,parentSchema:c,it:s}=i;c.then===void 0&&c.else===void 0&&(0,r.checkStrictMode)(s,'"if" without "then" and "else" is ignored');let l=o(s,"then"),m=o(s,"else");if(!l&&!m)return;let h=a.let("valid",!0),z=a.name("_valid");if(R(),i.reset(),l&&m){let b=a.let("ifClause");i.setParams({ifClause:b}),a.if(z,v("then",b),v("else",b))}else l?a.if(z,v("then")):a.if((0,t.not)(z),v("else"));i.pass(h,()=>i.error(!0));function R(){let b=i.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},z);i.mergeEvaluated(b)}function v(b,g){return()=>{let d=i.subschema({keyword:b},z);a.assign(h,z),i.mergeValidEvaluated(d,h),g?a.assign(g,(0,t._)`${b}`):i.setParams({ifClause:b})}}}};function o(i,a){let c=i.schema[a];return c!==void 0&&!(0,r.alwaysValidSchema)(i,c)}e.default=n})),Sy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_e(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:o,it:i}){o.if===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "if" is ignored`)}};e.default=r})),Ih=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wh(),r=cy(),n=Th(),o=uy(),i=ly(),a=al(),c=dy(),s=Eh(),l=my(),m=py(),h=fy(),z=hy(),R=gy(),v=vy(),b=_y(),g=Sy();function d(_=!1){let p=[h.default,z.default,R.default,v.default,b.default,g.default,c.default,s.default,a.default,l.default,m.default];return _?p.push(r.default,o.default):p.push(t.default,n.default),p.push(i.default),p}e.default=d})),yy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,o){let{gen:i,data:a,$data:c,schema:s,schemaCode:l,it:m}=n,{opts:h,errSchemaPath:z,schemaEnv:R,self:v}=m;if(!h.validateFormats)return;c?b():g();function b(){let d=i.scopeValue("formats",{ref:v.formats,code:h.code.formats}),_=i.const("fDef",(0,t._)`${d}[${l}]`),p=i.let("fType"),S=i.let("format");i.if((0,t._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>i.assign(p,(0,t._)`${_}.type || "string"`).assign(S,(0,t._)`${_}.validate`),()=>i.assign(p,(0,t._)`"string"`).assign(S,_)),n.fail$data((0,t.or)(w(),y()));function w(){return h.strictSchema===!1?t.nil:(0,t._)`${l} && !${S}`}function y(){let f=R.$async?(0,t._)`(${_}.async ? await ${S}(${a}) : ${S}(${a}))`:(0,t._)`${S}(${a})`,T=(0,t._)`(typeof ${S} == "function" ? ${f} : ${S}.test(${a}))`;return(0,t._)`${S} && ${S} !== true && ${p} === ${o} && !${T}`}}function g(){let d=v.formats[s];if(!d){w();return}if(d===!0)return;let[_,p,S]=y(d);_===o&&n.pass(f());function w(){if(h.strictSchema===!1){v.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${z}"`}}function y(T){let A=T instanceof RegExp?(0,t.regexpCode)(T):h.code.formats?(0,t._)`${h.code.formats}${(0,t.getProperty)(s)}`:void 0,F=i.scopeValue("formats",{key:s,ref:T,code:A});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,t._)`${F}.validate`]:["string",T,F]}function f(){if(typeof d=="object"&&!(d instanceof RegExp)&&d.async){if(!R.$async)throw new Error("async format in sync schema");return(0,t._)`await ${S}(${a})`}return typeof p=="function"?(0,t._)`${S}(${a})`:(0,t._)`${S}.test(${a})`}}}};e.default=r})),Ph=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=[yy().default];e.default=t})),kh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],e.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]})),Oh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=zh(),r=Rh(),n=Ih(),o=Ph(),i=kh(),a=[t.default,r.default,(0,n.default)(),o.default,i.metadataVocabulary,i.contentVocabulary];e.default=a})),by=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(r){r.Tag="tag",r.Mapping="mapping"})(t||(e.DiscrError=t={}))})),sl=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=by(),n=us(),o=Qr(),i=_e(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:c,tagName:s}})=>c===r.DiscrError.Tag?`tag "${s}" must be string`:`value of tag "${s}" must be in oneOf`,params:({params:{discrError:c,tag:s,tagName:l}})=>(0,t._)`{error: ${c}, tag: ${l}, tagValue: ${s}}`},code(c){let{gen:s,data:l,schema:m,parentSchema:h,it:z}=c,{oneOf:R}=h;if(!z.opts.discriminator)throw new Error("discriminator: requires discriminator option");let v=m.propertyName;if(typeof v!="string")throw new Error("discriminator: requires propertyName");if(m.mapping)throw new Error("discriminator: mapping is not supported");if(!R)throw new Error("discriminator: requires oneOf keyword");let b=s.let("valid",!1),g=s.const("tag",(0,t._)`${l}${(0,t.getProperty)(v)}`);s.if((0,t._)`typeof ${g} == "string"`,()=>d(),()=>c.error(!1,{discrError:r.DiscrError.Tag,tag:g,tagName:v})),c.ok(b);function d(){let S=p();s.if(!1);for(let w in S)s.elseIf((0,t._)`${g} === ${w}`),s.assign(b,_(S[w]));s.else(),c.error(!1,{discrError:r.DiscrError.Mapping,tag:g,tagName:v}),s.endIf()}function _(S){let w=s.name("valid"),y=c.subschema({keyword:"oneOf",schemaProp:S},w);return c.mergeEvaluated(y,t.Name),w}function p(){var S;let w={},y=T(h),f=!0;for(let M=0;M{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}})),jh=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let r=nl(),n=Oh(),o=sl(),i=$y(),a=["/properties"],c="http://json-schema.org/draft-07/schema";var s=class extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(R=>this.addVocabulary(R)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let R=this.opts.$data?this.$dataMetaSchema(i,a):i;this.addMetaSchema(R,c,!1),this.refs["http://json-schema.org/schema"]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}};e.Ajv=s,t.exports=e=s,t.exports.Ajv=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s;var l=Xr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var m=de();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return m._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return m.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return m.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return m.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return m.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return m.CodeGen}});var h=Ro();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return h.default}});var z=Qr();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return z.default}})})),Nh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=de(),r=dt(),n=us(),o=ol(),i={keyword:"$dynamicAnchor",schemaType:"string",code:s=>a(s,s.schema)};function a(s,l){let{gen:m,it:h}=s;h.schemaEnv.root.dynamicAnchors[l]=!0;let z=(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(l)}`,R=h.errSchemaPath==="#"?h.validateName:c(s);m.if((0,t._)`!${z}`,()=>m.assign(z,R))}e.dynamicAnchor=a;function c(s){let{schemaEnv:l,schema:m,self:h}=s.it,{root:z,baseId:R,localRefs:v,meta:b}=l.root,{schemaId:g}=h.opts,d=new n.SchemaEnv({schema:m,schemaId:g,root:z,baseId:R,localRefs:v,meta:b});return n.compileSchema.call(h,d),(0,o.getValidate)(s,d)}e.default=i})),xh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=de(),r=dt(),n=ol(),o={keyword:"$dynamicRef",schemaType:"string",code:a=>i(a,a.schema)};function i(a,c){let{gen:s,keyword:l,it:m}=a;if(c[0]!=="#")throw new Error(`"${l}" only supports hash fragment reference`);let h=c.slice(1);if(m.allErrors)z();else{let v=s.let("valid",!1);z(v),a.ok(v)}function z(v){if(m.schemaEnv.root.dynamicAnchors[h]){let b=s.let("_v",(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(h)}`);s.if(b,R(b,v),R(m.validateName,v))}else R(m.validateName,v)()}function R(v,b){return b?()=>s.block(()=>{(0,n.callRef)(a,v),s.let(b,!0)}):()=>(0,n.callRef)(a,v)}}e.dynamicRef=i,e.default=o})),zy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Nh(),r=_e(),n={keyword:"$recursiveAnchor",schemaType:"boolean",code(o){o.schema?(0,t.dynamicAnchor)(o,""):(0,r.checkStrictMode)(o.it,"$recursiveAnchor: false is ignored")}};e.default=n})),Ry=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xh(),r={keyword:"$recursiveRef",schemaType:"string",code:n=>(0,t.dynamicRef)(n,n.schema)};e.default=r})),Ch=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Nh(),r=xh(),n=zy(),o=Ry(),i=[t.default,r.default,n.default,o.default];e.default=i})),wy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=al(),r={keyword:"dependentRequired",type:"object",schemaType:"object",error:t.error,code:n=>(0,t.validatePropertyDeps)(n)};e.default=r})),Ty=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=al(),r={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0,t.validateSchemaDeps)(n)};e.default=r})),Ey=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_e(),r={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:o,it:i}){o.contains===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "contains" is ignored`)}};e.default=r})),Ah=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wy(),r=Ty(),n=Ey(),o=[t.default,r.default,n.default];e.default=o})),Iy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n=dt(),o={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:i})=>(0,t._)`{unevaluatedProperty: ${i.unevaluatedProperty}}`},code(i){let{gen:a,schema:c,data:s,errsCount:l,it:m}=i;if(!l)throw new Error("ajv implementation error");let{allErrors:h,props:z}=m;z instanceof t.Name?a.if((0,t._)`${z} !== true`,()=>a.forIn("key",s,g=>a.if(v(z,g),()=>R(g)))):z!==!0&&a.forIn("key",s,g=>z===void 0?R(g):a.if(b(z,g),()=>R(g))),m.props=!0,i.ok((0,t._)`${l} === ${n.default.errors}`);function R(g){if(c===!1){i.setParams({unevaluatedProperty:g}),i.error(),h||a.break();return}if(!(0,r.alwaysValidSchema)(m,c)){let d=a.name("valid");i.subschema({keyword:"unevaluatedProperties",dataProp:g,dataPropType:r.Type.Str},d),h||a.if((0,t.not)(d),()=>a.break())}}function v(g,d){return(0,t._)`!${g} || !${g}[${d}]`}function b(g,d){let _=[];for(let p in g)g[p]===!0&&_.push((0,t._)`${d} !== ${p}`);return(0,t.and)(..._)}}};e.default=o})),Py=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=_e(),n={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){let{gen:i,schema:a,data:c,it:s}=o,l=s.items||0;if(l===!0)return;let m=i.const("len",(0,t._)`${c}.length`);if(a===!1)o.setParams({len:l}),o.fail((0,t._)`${m} > ${l}`);else if(typeof a=="object"&&!(0,r.alwaysValidSchema)(s,a)){let z=i.var("valid",(0,t._)`${m} <= ${l}`);i.if((0,t.not)(z),()=>h(z,l)),o.ok(z)}s.items=!0;function h(z,R){i.forRange("i",R,m,v=>{o.subschema({keyword:"unevaluatedItems",dataProp:v,dataPropType:r.Type.Num},z),s.allErrors||i.if((0,t.not)(z),()=>i.break())})}}};e.default=n})),qh=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Iy(),r=Py(),n=[t.default,r.default];e.default=n})),ky=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}})),Oy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}})),jy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}})),Ny=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}})),xy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}})),Cy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),Ay=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),qy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ky(),r=Oy(),n=jy(),o=Ny(),i=xy(),a=Cy(),c=Ay(),s=["/properties"];function l(m){return[t,r,n,o,h(this,i),a,h(this,c)].forEach(z=>this.addMetaSchema(z,void 0,!1)),this;function h(z,R){return m?z.$dataMetaSchema(R,s):R}}e.default=l})),My=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2019=void 0;let r=nl(),n=Oh(),o=Ch(),i=Ah(),a=qh(),c=sl(),s=qy(),l="https://json-schema.org/draft/2019-09/schema";var m=class extends r.default{constructor(b={}){super({...b,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(o.default),n.default.forEach(b=>this.addVocabulary(b)),this.addVocabulary(i.default),this.addVocabulary(a.default),this.opts.discriminator&&this.addKeyword(c.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:b,meta:g}=this.opts;g&&(s.default.call(this,b),this.refs["http://json-schema.org/schema"]=l)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}};e.Ajv2019=m,t.exports=e=m,t.exports.Ajv2019=m,Object.defineProperty(e,"__esModule",{value:!0}),e.default=m;var h=Xr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return h.KeywordCxt}});var z=de();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return z._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return z.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return z.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return z.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return z.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return z.CodeGen}});var R=Ro();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return R.default}});var v=Qr();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return v.default}})})),Uy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=zh(),r=Rh(),n=Ih(),o=Ch(),i=Ah(),a=qh(),c=Ph(),s=kh(),l=[o.default,t.default,r.default,(0,n.default)(!0),c.default,s.metadataVocabulary,s.contentVocabulary,i.default,a.default];e.default=l})),Ly=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}})),Dy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}})),Vy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}})),Zy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}})),Fy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}})),Hy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}})),Jy=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),By=L(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),Ky=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ly(),r=Dy(),n=Vy(),o=Zy(),i=Fy(),a=Hy(),c=Jy(),s=By(),l=["/properties"];function m(h){return[t,r,n,o,i,z(this,a),c,z(this,s)].forEach(R=>this.addMetaSchema(R,void 0,!1)),this;function z(R,v){return h?R.$dataMetaSchema(v,l):v}}e.default=m})),Gy=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2020=void 0;let r=nl(),n=Uy(),o=sl(),i=Ky(),a="https://json-schema.org/draft/2020-12/schema";var c=class extends r.default{constructor(z={}){super({...z,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),n.default.forEach(z=>this.addVocabulary(z)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:z,meta:R}=this.opts;R&&(i.default.call(this,z),this.refs["http://json-schema.org/schema"]=a)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}};e.Ajv2020=c,t.exports=e=c,t.exports.Ajv2020=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var s=Xr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return s.KeywordCxt}});var l=de();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var m=Ro();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return m.default}});var h=Qr();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})),Wy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(M,D){return{validate:M,compare:D}}e.fullFormats={date:t(i,a),time:t(s(!0),l),"date-time":t(z(!0),R),"iso-time":t(s(),m),"iso-date-time":t(z(),v),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:d,"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:F,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:p,int32:{type:"number",validate:y},int64:{type:"number",validate:f},float:{type:"number",validate:T},double:{type:"number",validate:T},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),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,R),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),"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,v),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(M){return M%4===0&&(M%100!==0||M%400===0)}let n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(M){let D=n.exec(M);if(!D)return!1;let Y=+D[1],K=+D[2],fe=+D[3];return K>=1&&K<=12&&fe>=1&&fe<=(K===2&&r(Y)?29:o[K])}function a(M,D){if(M&&D)return M>D?1:M23||x>59||M&&!Ce)return!1;if(fe<=23&&Te<=59&&ze<60)return!0;let V=Te-x*ve,$=fe-k*ve-(V<0?1:0);return($===23||$===-1)&&(V===59||V===-1)&&ze<61}}function l(M,D){if(!(M&&D))return;let Y=new Date("2020-01-01T"+M).valueOf(),K=new Date("2020-01-01T"+D).valueOf();if(Y&&K)return Y-K}function m(M,D){if(!(M&&D))return;let Y=c.exec(M),K=c.exec(D);if(Y&&K)return M=Y[1]+Y[2]+Y[3],D=K[1]+K[2]+K[3],M>D?1:M=S}function f(M){return Number.isInteger(M)}function T(){return!0}let A=/[^\\]\\Z/;function F(M){if(A.test(M))return!1;try{return new RegExp(M),!0}catch{return!1}}})),Yy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=jh(),r=de(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},i={message:({keyword:c,schemaCode:s})=>(0,r.str)`should be ${o[c].okStr} ${s}`,params:({keyword:c,schemaCode:s})=>(0,r._)`{comparison: ${o[c].okStr}, limit: ${s}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:i,code(c){let{gen:s,data:l,schemaCode:m,keyword:h,it:z}=c,{opts:R,self:v}=z;if(!R.validateFormats)return;let b=new t.KeywordCxt(z,v.RULES.all.format.definition,"format");b.$data?g():d();function g(){let p=s.scopeValue("formats",{ref:v.formats,code:R.code.formats}),S=s.const("fmt",(0,r._)`${p}[${b.schemaCode}]`);c.fail$data((0,r.or)((0,r._)`typeof ${S} != "object"`,(0,r._)`${S} instanceof RegExp`,(0,r._)`typeof ${S}.compare != "function"`,_(S)))}function d(){let p=b.schema,S=v.formats[p];if(!S||S===!0)return;if(typeof S!="object"||S instanceof RegExp||typeof S.compare!="function")throw new Error(`"${h}": format "${p}" does not define "compare" function`);let w=s.scopeValue("formats",{key:p,ref:S,code:R.code.formats?(0,r._)`${R.code.formats}${(0,r.getProperty)(p)}`:void 0});c.fail$data(_(w))}function _(p){return(0,r._)`${p}.compare(${l}, ${m}) ${o[h].fail} 0`}},dependencies:["format"]};let a=c=>(c.addKeyword(e.formatLimitDefinition),c);e.default=a})),Xy=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let r=Wy(),n=Yy(),o=de(),i=new o.Name("fullFormats"),a=new o.Name("fastFormats"),c=(l,m={keywords:!0})=>{if(Array.isArray(m))return s(l,m,r.fullFormats,i),l;let[h,z]=m.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,i];return s(l,m.formats||r.formatNames,h,z),m.keywords&&(0,n.default)(l),l};c.get=(l,m="full")=>{let h=(m==="fast"?r.fastFormats:r.fullFormats)[l];if(!h)throw new Error(`Unknown format "${l}"`);return h};function s(l,m,h,z){var R,v;(R=(v=l.opts.code).formats)!==null&&R!==void 0||(v.formats=(0,o._)`require("ajv-formats/dist/formats").${z}`);for(let b of m)l.addFormat(b,h[b])}t.exports=e=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c})),Mh=jh(),Qy=My(),eb=Gy(),tb=Fo(Xy(),1),rb=tb.default;function rl(e){let t=new e({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return rb(t),t}var ls=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(e){this._userAjv=e!==void 0,this._ajv=e}get ajv(){return this._ajv??=rl(eb.Ajv2020)}_engineFor(e){if(this._userAjv)return this.ajv;let t=El(e,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return t==="2020-12"?this.ajv:t==="2019-09"?this._ajv2019??=rl(Qy.Ajv2019):this._ajvDraft7??=rl(Mh.Ajv)}getValidator(e){let t=this._engineFor(e),r="$id"in e&&typeof e.$id=="string"?t.getSchema(e.$id)??t.compile(e):t.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:t.errorsText(r.errors)}}},yT=Mh.Ajv;import cl from"node:process";var fE=2**31-1;var ab=8,sb=6e5;function cb(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??ab,roundTimeoutMs:e?.roundTimeoutMs??sb,legacyShim:e?.legacyShim??!0}}function Uh(e,t,r){if(r===null||typeof r!="object"||typeof r.method!="string")throw new ge(X.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let n=r,o=Lf(n);if(o===void 0)throw new ge(X.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${n.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:n,required:o}}function ub(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function ul(e,t){if(e==="tools/call")return{content:[{type:"text",text:t}],isError:!0};throw new ge(X.InternalError,t)}var lb=class{constructor(e){this._host=e}async fulfill(e,t,r,n,o){let{maxRounds:i,roundTimeoutMs:a}=this._host,c=n.mcpReq.signal,s=o,l=0;for(;;){if(l+=1,l>i)return ul(e,uh(e,i));let m=s.inputRequests,h=m!=null&&Object.keys(m).length>0,z=typeof s.requestState=="string"?s.requestState:void 0;if(!h&&z===void 0)throw new ge(X.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let R;if(h){let g=this._host.resolvedClientCapabilities(n),d=[];for(let[p,S]of Object.entries(m)){let{embedded:w,required:y}=Uh(e,p,S);if(w.method!=="roots/list"&&w.params===void 0)throw new ge(X.InternalError,`Handler for ${e} returned an input request '${p}' of kind '${w.method}' without params`);if(es(y,g)!==void 0)return ul(e,`Cannot request input '${p}' (${w.method}): the client on this 2025-era connection did not declare the required capability${g===void 0?" (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)":""}`);d.push([p,w])}let _=dh(c);try{let p={relatedRequestId:n.mcpReq.id,timeout:a,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:_.signal},S=await Promise.all(d.map(async([w,y])=>{try{return[w,await this._dispatchLeg(y,p)]}catch(f){throw _.abort(f),f}}));R=Object.fromEntries(S)}catch(p){if(c.aborted)throw p;return ul(e,`Fulfilling input required by '${e}' failed: ${p instanceof Error?p.message:String(p)}`)}finally{_.dispose()}}else await lh(ch,c);let v={...n,mcpReq:{...n.mcpReq,inputResponses:R,droppedInputResponseKeys:void 0,requestState:zo(z)}};if(z!==void 0){let g=await this._host.verifyRequestState(z,v,e);g!==void 0&&(v=Yu(v,g))}let b=await t(r,v);if(!fr(b))return b;s=b}}async _dispatchLeg(e,t){switch(e.method){case"elicitation/create":{let r=e.params;return r.mode==="url"&&r.elicitationId===void 0&&(r={...r,elicitationId:ub()}),await this._host.sendElicitation(r,t)}case"sampling/createMessage":return await this._host.sendSampling(e.params,t);case"roots/list":return await this._host.listRoots(e.params,t)}}},db=new Set(["tools/call","prompts/get","resources/read"]),mb,pb,fb;var ll=class extends Xu{_clientCapabilities;_clientVersion;static{mb=(e,t)=>{t.clientCapabilities!==void 0&&(e._clientCapabilities=t.clientCapabilities),t.clientInfo!==void 0&&(e._clientVersion=t.clientInfo)},pb=(e,t)=>{let r=t.filter(n=>!e._supportedProtocolVersions.includes(n));r.length>0&&(e._supportedProtocolVersions=[...e._supportedProtocolVersions,...r]),e.setRequestHandler("server/discover",()=>e._ondiscover())},fb=e=>e._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new lb({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,r)=>this._verifyRequestState(e,t,r),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new ls,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=cb(t?.inputRequired),t?.cacheHints!==void 0){for(let[r,n]of Object.entries(t.cacheHints))n!==void 0&&Yf(n,`cacheHints['${r}']`);this._cacheHints=t.cacheHints}this.setRequestHandler("initialize",r=>this._oninitialize(r)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),Au(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(e,t)=>{let r=t.sessionId||t.http?.req?.headers.get("mcp-session-id")||void 0,{level:n}=e.params,o=rs(Ht,n);return o.success&&this._loggingLevels.set(r,o.data),{}})}buildContext(e,t){let r=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(n,o,i)=>{if(!this._capabilities.logging)return Promise.resolve();let a;if(this._servedModernEra()){if(a=e.mcpReq.envelope?.[Ut],a===void 0)return Promise.resolve()}else a=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return a!==void 0&&this.LOG_LEVEL_SEVERITY.get(n)this.elicitInput(n,o),requestSampling:(n,o)=>this.createMessage(n,o)},http:r?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Ht.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return r?this.LOG_LEVEL_SEVERITY.get(e){let a=await t(o,i);if(fr(a))throw new ge(X.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return a}:async(o,i)=>{let a=n?await this._invokeInputRequiredCapableHandler(e,t,o,i):await t(o,i);if(fr(a)){if(!n)throw new ge(X.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return a}return r===void 0?a:Wf(a,r)}}return async(r,n)=>{let o=Yr(this._negotiatedProtocolVersion),i=o.validateRequest("tools/call",r);if(!i.ok)throw new ge(i.reason==="not-in-era"?X.InternalError:X.InvalidParams,i.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${i.message}`);let a=await this._invokeInputRequiredCapableHandler("tools/call",t,r,n);if(fr(a))return a;let c=qu(a),s=o.validateResult("tools/call",c);if(!s.ok)throw new ge(s.reason==="not-in-era"?X.InternalError:X.InvalidParams,s.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${s.message}`);return s.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&$o(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,r,n){let o=this._servedModernEra(),i=n.mcpReq.requestState();if(i!==void 0&&typeof i!="string")throw new ge(X.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let a=n;if(typeof i=="string"){let h=await this._verifyRequestState(i,n,e);h!==void 0&&(a=Yu(n,h))}let c;try{c=await t(r,a)}catch(h){throw h instanceof ge&&h.code===X.UrlElicitationRequired&&o?new ge(X.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):h}if(!fr(c))return c;if(!o){if(!this._inputRequiredServing.legacyShim)throw new ge(X.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??cr}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,r,a,c)}let s=c.inputRequests,l=s!=null&&Object.keys(s).length>0,m=typeof c.requestState=="string";if(!l&&!m)throw new ge(X.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let h=this._inputRequestCapabilityView(n);for(let[z,R]of Object.entries(s)){let{embedded:v,required:b}=Uh(e,z,R),g=es(b,h);if(g!==void 0)throw new ts({requiredCapabilities:g},`Cannot request input '${z}' (${v.method}): the request's client capabilities do not declare the required capability`)}}return c}async _verifyRequestState(e,t,r){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(n){throw this.onerror?.(new Error(`requestState verification rejected ${r}: ${n instanceof Error?n.message:String(n)}`)),new ge(X.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[wt]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new le(he.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:"2026-07-28"})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new le(he.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new le(he.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new le(he.CapabilityNotSupported,`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 new le(he.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new le(he.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new le(he.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new le(he.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new le(he.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"completion/complete":if(!this._capabilities.completions)throw new le(he.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new le(he.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new le(he.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new le(he.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new le(he.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let r=Df(this._supportedProtocolVersions),n=r.includes(t)?t:r[0]??cr;return this._negotiatedProtocolVersion=n,this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Au(this._supportedProtocolVersions),capabilities:hb(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(e,t){if(this._assertPushApiInServedEra("sampling/createMessage"),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new le(he.CapabilityNotSupported,"Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages.at(-1),a=Array.isArray(i.content)?i.content:[i.content],c=a.some(h=>h.type==="tool_result"),s=e.messages.length>1?e.messages.at(-2):void 0,l=s?Array.isArray(s.content)?s.content:[s.content]:[],m=l.some(h=>h.type==="tool_use");if(c){if(a.some(h=>h.type!=="tool_result"))throw new ge(X.InvalidParams,"The last message must contain only tool_result content if any is present");if(!m)throw new ge(X.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(m){let h=new Set(l.filter(R=>R.type==="tool_use").map(R=>R.id)),z=new Set(a.filter(R=>R.type==="tool_result").map(R=>R.toolUseId));if(h.size!==z.size||![...h].every(R=>z.has(R)))throw new ge(X.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let r=!!(e.tools||e.toolChoice),n=await this.request({method:"sampling/createMessage",params:e},t),o=this._wireCodec().samplingResultVariant(r,n);if(!o.ok)throw new le(he.InvalidResult,`Invalid sampling/createMessage result: ${o.reason==="invalid"?o.message:o.reason}`);return o.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra("elicitation/create"),e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new le(he.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new le(he.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,r){let n=e.mode??"form",o=r?.validateAcceptedContent??!0;switch(n){case"url":{let i=e;return this.request({method:"elicitation/create",params:i},t)}case"form":{let i=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:i},t);if(o&&a.action==="accept"&&a.content&&i.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!c.valid)throw new ge(X.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(c){throw c instanceof ge?c:new ge(X.InternalError,`Error validating elicitation response: ${c instanceof Error?c.message:String(c)}`)}return a}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new le(he.CapabilityNotSupported,"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._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:e},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"})}};function hb(e){return{...e}}var Lh=class{_readBuffer;_started=!1;_closed=!1;constructor(e=cl.stdin,t=cl.stdout,r){this._stdin=e,this._stdout=t,this._readBuffer=new el({maxBufferSize:r?.maxBufferSize})}onclose;onerror;onmessage;_ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(t){this.onerror?.(t),this.close().catch(()=>{})}};_onerror=e=>{this.onerror?.(e)};_onstdouterror=e=>{this.onerror?.(e),this.close().catch(()=>{})};async start(){if(this._started)throw new 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),this._stdout.on("error",this._onstdouterror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._closed||(this._closed=!0,this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdout.off("error",this._onstdouterror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(e){return this._closed?Promise.reject(new Error("StdioServerTransport is closed")):new Promise((t,r)=>{let n=tl(e),o=!1,i=c=>{o||(o=!0,this._stdout.off("error",i),this._stdout.off("drain",a),r(c))},a=()=>{o||(o=!0,this._stdout.off("error",i),this._stdout.off("drain",a),t())};if(this._stdout.once("error",i),this._stdout.write(n)){if(o)return;o=!0,this._stdout.off("error",i),t()}else o||this._stdout.once("drain",a)})}};import{appendFileSync as pt,existsSync as vt,readFileSync as Rb,writeFileSync as Ze}from"node:fs";import{setTimeout as Me}from"node:timers/promises";var fs=process.env.TEST_ACCOUNT_NAME??"unknown",hs=process.env.TEST_INCLUDE_RESPONSE_TOKEN==="true"?`${fs}:${process.env.API_TOKEN??""}`:fs,Dh=Number(process.env.TEST_LIST_TOOLS_DELAY_MS??"0"),Vh=Number(process.env.TEST_LIST_TOOLS_START_DELAY_MS??"0"),Zh=Number(process.env.TEST_LIST_TOOLS_DELAY_AFTER_NOTIFICATION_MS??"0"),Fh=Number(process.env.TEST_LIST_RESOURCES_DELAY_MS??"0"),Hh=Number(process.env.TEST_LIST_PROMPTS_DELAY_MS??"0"),wb=process.env.TEST_LIST_TOOLS_PROGRESS==="true",Tb=process.env.TEST_LIST_RESOURCES_PROGRESS==="true",Eb=process.env.TEST_LIST_RESOURCE_TEMPLATES_PROGRESS==="true",Ib=process.env.TEST_LIST_PROMPTS_PROGRESS==="true",Jh=Number(process.env.TEST_CALL_TOOL_DELAY_MS??"0"),Pb=process.env.TEST_CALL_TOOL_PROGRESS==="true",Bh=process.env.TEST_CALL_TOOL_PROGRESS_MESSAGE,Kh=Number(process.env.TEST_READ_RESOURCE_DELAY_MS??"0"),Gh=Number(process.env.TEST_GET_PROMPT_DELAY_MS??"0"),kb=process.env.TEST_RESOURCE_NAME??"Current account",zg=process.env.TEST_RESOURCE_URI??"account://current",Ob=process.env.TEST_RESOURCE_TEMPLATE_NAME??"account",gs=process.env.TEST_RESOURCE_TEMPLATE_URI,jb=process.env.TEST_RESOURCE_TEMPLATES_UNSUPPORTED==="true",ys=process.env.TEST_RESOURCE_SUBSCRIPTIONS==="true",ps=process.env.TEST_RESOURCE_SUBSCRIPTION_STATEFUL_UPDATES==="true",Nb=process.env.TEST_FAIL_SUBSCRIBE==="true",Wh=process.env.TEST_RESOURCE_UPDATE_URI,Yh=Number(process.env.TEST_RESOURCE_UPDATE_DELAY_MS??"0"),Xh=Number(process.env.TEST_SUBSCRIBE_START_DELAY_MS??"0"),Qh=Number(process.env.TEST_SUBSCRIBE_DELAY_MS??"0"),eg=Number(process.env.TEST_UNSUBSCRIBE_DELAY_MS??"0"),tg=process.env.TEST_SUBSCRIBE_COUNT_PATH,rg=process.env.TEST_UNSUBSCRIBE_COUNT_PATH,ng=process.env.TEST_SUBSCRIBE_STARTED_PATH,xb=process.env.TEST_NOTIFY_TOOL_LIST_CHANGE_ON_LIST_TOOLS==="true",Cb=process.env.TEST_NOTIFY_TOOL_LIST_CHANGE_ON_FIRST_LIST_TOOLS==="true",Ab=process.env.TEST_TOOL_LIST_CHANGES_AFTER_FIRST_REQUEST==="true",qb=process.env.TEST_NOTIFY_LIST_CHANGES_ON_CALL_TOOL==="true",Rg=process.env.TEST_PROMPT_NAME??"account_prompt",Sl=!1,yl=0,vs=process.env.TEST_PAGINATE_CAPABILITIES==="true",og=process.env.TEST_PAGINATE_TOOLS==="true",Mb=process.env.TEST_SECOND_RESOURCE_NAME??"Second account",Ub=process.env.TEST_SECOND_RESOURCE_URI??"account://second",Lb=process.env.TEST_SECOND_PROMPT_NAME??"second_prompt",ig=process.env.TEST_ADDITIONAL_RESOURCE_URI,ag=process.env.TEST_RESOURCE_ICON_URI,_s=process.env.TEST_PROMPT_ICON_URI,dl=process.env.TEST_PROMPT_RESOURCE_URI,ml=process.env.TEST_FAIL_ON_RESTART_PATH,sg=process.env.TEST_FAIL_LIST_RESOURCES_PATH,cg=process.env.TEST_FAIL_LIST_PROMPTS_PATH,Ss=process.env.TEST_CRASH_ON_CALL_TOOL_PATH,ug=process.env.TEST_CRASH_ON_CALL_TOOL_OBSERVED_PATH,lg=process.env.TEST_CRASH_AFTER_INITIALIZED_PATH,dg=process.env.TEST_START_COUNT_PATH,mg=process.env.TEST_INITIALIZED_PATH,pg=process.env.TEST_CREATE_ITEM_COUNT_PATH,fg=process.env.TEST_CALL_TOOL_STARTED_PATH,hg=process.env.TEST_CANCELLED_PATH,gg=process.env.TEST_FAIL_INITIALIZE==="true",pl=process.env.TEST_CLIENT_INFO_PATH,wo=process.env.TEST_STDERR_MESSAGE,ds=Number(process.env.TEST_STDERR_SPLIT_AT??"0"),ms=process.env.TEST_HANG_ON_START_PATH,vg=process.env.TEST_HANG_ON_START_READY_PATH,fl=Number(process.env.TEST_SHUTDOWN_DELAY_MS??"0"),hl=process.env.TEST_SHUTDOWN_END_PATH,Db=process.env.TEST_INCLUDE_IDENTITY_TOOL==="true",gl=Number(process.env.TEST_OVERSIZED_IDENTITY_RESPONSE_REPEAT??"0"),bl=Number.isSafeInteger(gl)&&gl>0?"identity-response-secret".repeat(gl):void 0,Vb=bl===void 0?process.env.TEST_IDENTITY_RESPONSE??JSON.stringify({login:fs}):JSON.stringify({login:bl}),Zb=process.env.TEST_IDENTITY_SCHEMA==="min-properties"?{type:"object",properties:{account:{type:"string"}},minProperties:1}:process.env.TEST_IDENTITY_SCHEMA==="all-of-required"?{type:"object",properties:{account:{type:"string"}},allOf:[{required:["account"]}]}:process.env.TEST_IDENTITY_SCHEMA==="additional-properties-false"?{type:"object",properties:{},additionalProperties:!1}:{type:"object",properties:{}},$l=process.env.TEST_INCLUDE_SAFE_READ_TOOL==="true"?"get_capabilities":void 0,_g=process.env.TEST_SAFE_READ_CALL_PATH,Fb=process.env.TEST_SAFE_READ_RESPONSE??"safe-read",Sg=Tg(process.env.TEST_SAFE_READ_ANNOTATIONS,"TEST_SAFE_READ_ANNOTATIONS"),Hb=process.env.TEST_SAFE_READ_SCHEMA==="required"?{type:"object",properties:{account:{type:"string"}},required:["account"]}:process.env.TEST_SAFE_READ_SCHEMA==="all-of-required"?{type:"object",properties:{},allOf:[{required:["account"]}]}:{type:"object",properties:{}},vl=0,yg=process.env.TEST_ISOLATION_REPORT_PATH;if(yg){let e=process.env.OAUTH_CREDENTIAL_PATH;if(!e)throw new Error("test isolation fixture requires OAUTH_CREDENTIAL_PATH");let t=Rb(e,"utf8");Ze(yg,JSON.stringify({home:process.env.HOME,xdgConfigHome:process.env.XDG_CONFIG_HOME,xdgCacheHome:process.env.XDG_CACHE_HOME,xdgDataHome:process.env.XDG_DATA_HOME,xdgStateHome:process.env.XDG_STATE_HOME,xdgRuntimeDir:process.env.XDG_RUNTIME_DIR,credentialPath:e,credential:t})),process.env.TEST_ISOLATION_EMIT_CREDENTIAL==="true"&&process.stderr.write(`test isolated credential: ${t} +`);let r=process.env.TEST_ISOLATION_EMIT_CREDENTIAL_FIELD;if(r){let n=JSON.parse(t)[r];if(typeof n!="string")throw new Error("test isolation fixture requires a string credential field");process.stderr.write(`test isolated credential field: ${n} +`)}}dg&&pt(dg,`1 +`);if(process.env.TEST_HANG_ON_START==="true"||ms&&vt(ms))if(vg&&Ze(vg,"ready"),ms)for(;vt(ms);)await Me(5);else for(;;)await Me(1e3);(hl||fl>0)&&process.stdin.once("end",()=>{hl&&Ze(hl,"ended"),fl>0&&Me(fl).then(()=>process.exit(0))});process.env.TEST_IGNORE_SIGTERM==="true"&&process.on("SIGTERM",()=>{});wo&&(ds>0&&ds{mg&&Ze(mg,"initialized"),lg&&vt(lg)&&Me(0).then(()=>process.exit(1))};function Tg(e,t){if(e!==void 0)try{return JSON.parse(e)}catch{throw new Error(`${t} must contain valid JSON`)}}(gg||pl)&&Pe.setRequestHandler("initialize",async e=>{if(pl&&Ze(pl,JSON.stringify(e.params.clientInfo)),gg)throw new Error(`test initialize failure: ${process.env.API_TOKEN}`);return{protocolVersion:e.params.protocolVersion,capabilities:{tools:{},resources:ys?{subscribe:!0}:{},prompts:{}},serverInfo:{name:"fake-upstream",version:"1.0.0"}}});Pe.setRequestHandler("tools/list",async e=>{vl+=1;let t=Ab&&vl>1;if(Vh>0&&await Me(Vh),process.env.TEST_LIST_TOOLS_STARTED_PATH&&Ze(process.env.TEST_LIST_TOOLS_STARTED_PATH,"started"),process.env.TEST_LIST_TOOLS_COUNT_PATH&&pt(process.env.TEST_LIST_TOOLS_COUNT_PATH,`1 +`),Dh>0&&await Me(Dh),wb&&e.params._meta?.progressToken!==void 0&&await Pe.notification({method:"notifications/progress",params:{progressToken:e.params._meta.progressToken,progress:1,total:2}}),process.env.TEST_FAIL_LIST_TOOLS==="true")throw new Error(`test tool list failure: ${process.env.TEST_ERROR_MESSAGE??process.env.API_TOKEN}`);(xb||Cb&&vl===1)&&await Pe.sendToolListChanged(),Zh>0&&await Me(Zh);let r=og&&e.params?.cursor==="next";return{tools:[...wg?[{name:"exec",description:"Execute a PostHog command.",inputSchema:{type:"object",properties:{command:{type:"string"},context:{type:"string"}},required:["command","context"],additionalProperties:!1}}]:r?[{name:"whoami_second",description:"Return the second injected account.",inputSchema:bg},{name:"echo_second",description:"Echo a second message.",inputSchema:{type:"object",properties:{message:{type:"string"}},required:["message"]}},{name:"create_second_item",description:"Create a second item.",inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]}}]:[{name:t?"whoami_reloaded":"whoami",description:process.env.TEST_INCLUDE_DISCOVERY_TOKEN==="true"?`Return the injected account ${process.env.API_TOKEN}`:"Return the injected account.",inputSchema:bg},{name:t?"echo_reloaded":"echo",description:"Echo a message.",inputSchema:{type:"object",properties:{message:{type:"string"}},required:["message"]}},{name:t?"create_reloaded_item":"create_item",description:"Create an item.",inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},...$g===void 0?{}:{annotations:$g}}],...Db&&!r?[{name:"identity",description:"Return the configured account identity.",inputSchema:Zb}]:[],...$l&&!r?[{name:$l,description:"Run the provider-declared empty-object readiness probe.",inputSchema:Hb,...Sg===void 0?{}:{annotations:Sg}}]:[],...process.env.TEST_INCLUDE_MANAGEMENT_TOOL==="true"?[{name:"miftah_health",description:"Collides with a reserved Miftah management tool.",inputSchema:{type:"object",properties:{}}}]:[],...process.env.TEST_INCLUDE_MIFTAH_PREFIX_TOOL==="true"?[{name:"miftah_custom",description:"An upstream tool with a Miftah-looking name.",inputSchema:{type:"object",properties:{}}}]:[]],...og&&!r?{nextCursor:"next"}:{}}});Pe.setRequestHandler("tools/call",async e=>{if(fg&&Ze(fg,"started"),Ss&&vt(Ss))return Me(0).then(()=>process.exit(1)),new Promise(()=>{});if(process.env.TEST_CALL_TOOL_COUNT_PATH&&pt(process.env.TEST_CALL_TOOL_COUNT_PATH,`1 +`),e.params.name==="create_item"&&pg&&pt(pg,`1 +`),process.env.TEST_FAIL_CALL_TOOL==="true")throw new Error(`test tool call failure: ${process.env.API_TOKEN}`);return process.env.TEST_RETURN_CALL_TOOL_ERROR==="true"?{content:[{type:"text",text:"test tool returned an error result"}],isError:!0}:(Pb&&e.params._meta?.progressToken!==void 0&&await Pe.notification({method:"notifications/progress",params:{progressToken:e.params._meta.progressToken,progress:1,total:2,...Bh===void 0?{}:{message:Bh}}}),qb&&await Promise.all([Pe.sendToolListChanged(),Pe.sendResourceListChanged(),Pe.sendPromptListChanged()]),Jh>0&&await Me(Jh),wg&&e.params.name==="exec"?{content:[{type:"text",text:`exec:${String(e.params.arguments?.command??"")}`}]}:e.params.name==="whoami"?{content:[{type:"text",text:bl??fs}]}:e.params.name==="identity"?{content:[{type:"text",text:Vb}]}:e.params.name===$l?(_g&&Ze(_g,JSON.stringify({name:e.params.name,arguments:e.params.arguments??{}})),{content:[{type:"text",text:Fb}]}):e.params.name==="echo"?{content:[{type:"text",text:String(e.params.arguments?.message??"")}]}:{content:[{type:"text",text:`created:${String(e.params.arguments?.name??"")}`}]})});Pe.setNotificationHandler("notifications/cancelled",e=>{hg&&pt(hg,`${e.params.requestId} +`)});Pe.setRequestHandler("resources/list",async e=>{if(process.env.TEST_LIST_RESOURCES_COUNT_PATH&&pt(process.env.TEST_LIST_RESOURCES_COUNT_PATH,`1 +`),process.env.TEST_LIST_RESOURCES_STARTED_PATH&&Ze(process.env.TEST_LIST_RESOURCES_STARTED_PATH,"started"),Fh>0&&await Me(Fh),Tb&&e.params._meta?.progressToken!==void 0&&await Pe.notification({method:"notifications/progress",params:{progressToken:e.params._meta.progressToken,progress:1,total:2}}),process.env.TEST_FAIL_LIST_RESOURCES==="true"||sg&&vt(sg))throw new Error(`test resource discovery failure: ${process.env.API_TOKEN}`);let t=vs&&e.params?.cursor==="next";return{resources:[{uri:t?Ub:zg,name:process.env.TEST_INCLUDE_DISCOVERY_TOKEN==="true"?`Current account ${process.env.API_TOKEN}`:t?Mb:kb,mimeType:"text/plain",...ag?{icons:[{src:ag}]}:{}}],...vs&&!t?{nextCursor:"next"}:{}}});jb||Pe.setRequestHandler("resources/templates/list",async e=>(Eb&&e.params._meta?.progressToken!==void 0&&await Pe.notification({method:"notifications/progress",params:{progressToken:e.params._meta.progressToken,progress:1,total:2}}),{resourceTemplates:gs===void 0?[]:[{uriTemplate:gs,name:Ob,mimeType:"text/plain"}]}));Pe.setRequestHandler("resources/read",async e=>{if(process.env.TEST_READ_RESOURCE_COUNT_PATH&&pt(process.env.TEST_READ_RESOURCE_COUNT_PATH,`1 +`),process.env.TEST_READ_RESOURCE_STARTED_PATH&&Ze(process.env.TEST_READ_RESOURCE_STARTED_PATH,"started"),Kh>0&&await Me(Kh),process.env.TEST_FAIL_READ_RESOURCE==="true")throw new Error(`test resource read failure: ${process.env.TEST_ERROR_URI??process.env.API_TOKEN}`);return{contents:[{uri:gs!==void 0&&new ns(gs).match(e.params.uri)!==null?e.params.uri:zg,text:hs,mimeType:"text/plain"},...ig?[{uri:ig,text:hs,mimeType:"text/plain"}]:[]]}});Pe.setRequestHandler("resources/subscribe",async()=>{if(!ys)throw new Error("test upstream does not support resource subscriptions");if(Xh>0&&await Me(Xh),ng&&Ze(ng,"started"),tg&&pt(tg,`1 +`),Qh>0&&await Me(Qh),Nb)throw new Error("test subscribe failure");let e=ps?++yl:void 0;if(ps&&(Sl=!0),Wh){let t=async()=>{ps&&(!Sl||yl!==e)||await Pe.sendResourceUpdated({uri:Wh})};Yh>0?Me(Yh).then(t):await t()}return{}});Pe.setRequestHandler("resources/unsubscribe",async()=>{if(!ys)throw new Error("test upstream does not support resource subscriptions");return rg&&pt(rg,`1 +`),eg>0&&await Me(eg),ps&&(Sl=!1,yl+=1),{}});Pe.setRequestHandler("prompts/list",async e=>{if(process.env.TEST_LIST_PROMPTS_COUNT_PATH&&pt(process.env.TEST_LIST_PROMPTS_COUNT_PATH,`1 +`),process.env.TEST_LIST_PROMPTS_STARTED_PATH&&Ze(process.env.TEST_LIST_PROMPTS_STARTED_PATH,"started"),Hh>0&&await Me(Hh),Ib&&e.params._meta?.progressToken!==void 0&&await Pe.notification({method:"notifications/progress",params:{progressToken:e.params._meta.progressToken,progress:1,total:2}}),process.env.TEST_FAIL_LIST_PROMPTS==="true"||cg&&vt(cg))throw new Error(`test prompt discovery failure: ${process.env.API_TOKEN}`);let t=vs&&e.params?.cursor==="next";return{prompts:[{name:t?Lb:Rg,description:process.env.TEST_INCLUDE_DISCOVERY_TOKEN==="true"?`Account prompt ${process.env.API_TOKEN}`:t?"Second account prompt":"Account prompt",..._s?{icons:[{src:_s}]}:{}}],...vs&&!t?{nextCursor:"next"}:{}}});Pe.setRequestHandler("prompts/get",async()=>{if(process.env.TEST_GET_PROMPT_COUNT_PATH&&pt(process.env.TEST_GET_PROMPT_COUNT_PATH,`1 +`),process.env.TEST_GET_PROMPT_STARTED_PATH&&Ze(process.env.TEST_GET_PROMPT_STARTED_PATH,"started"),Gh>0&&await Me(Gh),process.env.TEST_FAIL_GET_PROMPT==="true")throw new Error(`test prompt get failure: ${process.env.TEST_ERROR_URI??process.env.API_TOKEN}`);return{description:Rg,messages:[{role:"user",content:{type:"text",text:hs}},...dl?[{role:"assistant",content:{type:"resource_link",uri:dl,name:"Account resource",..._s?{icons:[{src:_s}]}:{}}},{role:"assistant",content:{type:"resource",resource:{uri:dl,text:hs,mimeType:"text/plain"}}}]:[]]}});await Pe.connect(new Lh); diff --git a/tests/fixtures/fake-upstream-runtime.mjs b/tests/fixtures/fake-upstream-runtime.mjs index 78132d4b..b3dc6800 100644 --- a/tests/fixtures/fake-upstream-runtime.mjs +++ b/tests/fixtures/fake-upstream-runtime.mjs @@ -1,22 +1,7 @@ -import { Server } from "@modelcontextprotocol/sdk/server/index.js"; -import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; -import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js"; +import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { Server, UriTemplate } from "@modelcontextprotocol/server"; import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { setTimeout as delay } from "node:timers/promises"; -import { - CancelledNotificationSchema, - CallToolRequestSchema, - GetPromptRequestSchema, - InitializeRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ListToolsRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema -} from "@modelcontextprotocol/sdk/types.js"; - const account = process.env.TEST_ACCOUNT_NAME ?? "unknown"; const responseText = process.env.TEST_INCLUDE_RESPONSE_TOKEN === "true" ? `${account}:${process.env.API_TOKEN ?? ""}` : account; @@ -251,7 +236,7 @@ function parseOptionalJson(value, variableName) { } if (failInitialize || clientInfoPath) { - server.setRequestHandler(InitializeRequestSchema, async (request) => { + server.setRequestHandler('initialize', async (request) => { if (clientInfoPath) { writeFileSync(clientInfoPath, JSON.stringify(request.params.clientInfo)); } @@ -266,7 +251,7 @@ if (failInitialize || clientInfoPath) { }); } -server.setRequestHandler(ListToolsRequestSchema, async (request) => { +server.setRequestHandler('tools/list', async (request) => { toolListRequests += 1; const changedToolList = changeToolListAfterFirstRequest && toolListRequests > 1; if (listToolsStartDelayMs > 0) { @@ -415,7 +400,7 @@ server.setRequestHandler(ListToolsRequestSchema, async (request) => { }; }); -server.setRequestHandler(CallToolRequestSchema, async (request) => { +server.setRequestHandler('tools/call', async (request) => { if (callToolStartedPath) { writeFileSync(callToolStartedPath, "started"); } @@ -480,13 +465,13 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { return { content: [{ type: "text", text: `created:${String(request.params.arguments?.name ?? "")}` }] }; }); -server.setNotificationHandler(CancelledNotificationSchema, (notification) => { +server.setNotificationHandler('notifications/cancelled', (notification) => { if (cancelledPath) { appendFileSync(cancelledPath, `${notification.params.requestId}\n`); } }); -server.setRequestHandler(ListResourcesRequestSchema, async (request) => { +server.setRequestHandler('resources/list', async (request) => { if (process.env.TEST_LIST_RESOURCES_COUNT_PATH) { appendFileSync(process.env.TEST_LIST_RESOURCES_COUNT_PATH, "1\n"); } @@ -523,7 +508,7 @@ server.setRequestHandler(ListResourcesRequestSchema, async (request) => { }); if (!resourceTemplatesUnsupported) { - server.setRequestHandler(ListResourceTemplatesRequestSchema, async (request) => { + server.setRequestHandler('resources/templates/list', async (request) => { if (listResourceTemplatesProgress && request.params._meta?.progressToken !== undefined) { await server.notification({ method: "notifications/progress", @@ -539,7 +524,7 @@ if (!resourceTemplatesUnsupported) { }); } -server.setRequestHandler(ReadResourceRequestSchema, async (request) => { +server.setRequestHandler('resources/read', async (request) => { if (process.env.TEST_READ_RESOURCE_COUNT_PATH) { appendFileSync(process.env.TEST_READ_RESOURCE_COUNT_PATH, "1\n"); } @@ -562,7 +547,7 @@ server.setRequestHandler(ReadResourceRequestSchema, async (request) => { }; }); -server.setRequestHandler(SubscribeRequestSchema, async () => { +server.setRequestHandler('resources/subscribe', async () => { if (!resourceSubscriptions) throw new Error("test upstream does not support resource subscriptions"); if (subscribeStartDelayMs > 0) await delay(subscribeStartDelayMs); if (subscribeStartedPath) writeFileSync(subscribeStartedPath, "started"); @@ -590,7 +575,7 @@ server.setRequestHandler(SubscribeRequestSchema, async () => { return {}; }); -server.setRequestHandler(UnsubscribeRequestSchema, async () => { +server.setRequestHandler('resources/unsubscribe', async () => { if (!resourceSubscriptions) throw new Error("test upstream does not support resource subscriptions"); if (unsubscribeCountPath) appendFileSync(unsubscribeCountPath, "1\n"); if (unsubscribeDelayMs > 0) await delay(unsubscribeDelayMs); @@ -601,7 +586,7 @@ server.setRequestHandler(UnsubscribeRequestSchema, async () => { return {}; }); -server.setRequestHandler(ListPromptsRequestSchema, async (request) => { +server.setRequestHandler('prompts/list', async (request) => { if (process.env.TEST_LIST_PROMPTS_COUNT_PATH) { appendFileSync(process.env.TEST_LIST_PROMPTS_COUNT_PATH, "1\n"); } @@ -636,7 +621,7 @@ server.setRequestHandler(ListPromptsRequestSchema, async (request) => { }; }); -server.setRequestHandler(GetPromptRequestSchema, async () => { +server.setRequestHandler('prompts/get', async () => { if (process.env.TEST_GET_PROMPT_COUNT_PATH) { appendFileSync(process.env.TEST_GET_PROMPT_COUNT_PATH, "1\n"); } diff --git a/tests/helpers/fake-remote-upstream.ts b/tests/helpers/fake-remote-upstream.ts index 0a17fa1d..63e16a7f 100644 --- a/tests/helpers/fake-remote-upstream.ts +++ b/tests/helpers/fake-remote-upstream.ts @@ -1,24 +1,14 @@ import { createHash, randomUUID } from "node:crypto"; import { createServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from "node:http"; import { setTimeout as delay } from "node:timers/promises"; -import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js"; -import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; -import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; -import { - CancelledNotificationSchema, - CallToolRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListToolsRequestSchema, - McpError, - ReadResourceRequestSchema -} from "@modelcontextprotocol/sdk/types.js"; -import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; +import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse"; +import { Server as McpServer, ProtocolError } from "@modelcontextprotocol/server"; +import type { FetchLike } from "@modelcontextprotocol/server"; interface StreamableSession { server: McpServer; - transport: StreamableHTTPServerTransport; + transport: NodeStreamableHTTPServerTransport; } interface SseSession { @@ -167,7 +157,7 @@ export async function startFakeRemoteUpstream(options: FakeRemoteUpstreamOptions } const server = createMcpServer(request.headers["x-profile"], options, callToolState); - const transport = new StreamableHTTPServerTransport({ + const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: randomUUID, onsessioninitialized: (createdSessionId) => { streamableSessions.set(createdSessionId, { server, transport }); @@ -498,7 +488,7 @@ export async function startOAuthCompatibilityProbe( } const server = createMcpServer(undefined, {}, callToolState); - const transport = new StreamableHTTPServerTransport({ + const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: randomUUID, onsessioninitialized: (createdSessionId) => { sessions.set(createdSessionId, { server, transport }); @@ -566,18 +556,18 @@ function createMcpServer( { capabilities: { tools: {}, resources: {}, prompts: {} } } ); - server.setRequestHandler(ListToolsRequestSchema, async () => ({ + server.setRequestHandler('tools/list', async () => ({ tools: [ { name: "whoami", description: "Return the request profile.", inputSchema: { type: "object", properties: {} } } ] })); - server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { + server.setRequestHandler('tools/call', async (request, ctx) => { callToolState.toolCallRequests += 1; if (options.callToolError) { - throw new McpError(options.callToolError.code, options.callToolError.message); + throw new ProtocolError(options.callToolError.code, options.callToolError.message); } if (options.emitCallToolProgress && request.params._meta?.progressToken !== undefined) { - await extra.sendNotification({ + await ctx.mcpReq.notify({ method: "notifications/progress", params: { progressToken: request.params._meta.progressToken, progress: 1, total: 2 } }); @@ -585,19 +575,19 @@ function createMcpServer( if (options.callToolDelayMs && options.callToolDelayMs > 0) await delay(options.callToolDelayMs); return { content: [{ type: "text", text: profile }] }; }); - server.setNotificationHandler(CancelledNotificationSchema, () => { + server.setNotificationHandler('notifications/cancelled', () => { callToolState.cancelledNotifications += 1; }); - server.setRequestHandler(ListResourcesRequestSchema, async () => ({ + server.setRequestHandler('resources/list', async () => ({ resources: [{ uri: "account://current", name: "Current profile", mimeType: "text/plain" }] })); - server.setRequestHandler(ReadResourceRequestSchema, async () => ({ + server.setRequestHandler('resources/read', async () => ({ contents: [{ uri: "account://current", text: profile, mimeType: "text/plain" }] })); - server.setRequestHandler(ListPromptsRequestSchema, async () => ({ + server.setRequestHandler('prompts/list', async () => ({ prompts: [{ name: "account_prompt", description: "Current profile prompt." }] })); - server.setRequestHandler(GetPromptRequestSchema, async () => ({ + server.setRequestHandler('prompts/get', async () => ({ messages: [{ role: "user", content: { type: "text", text: profile } }] })); return server; diff --git a/tests/http-server.test.ts b/tests/http-server.test.ts index 955709c9..ef207a9f 100644 --- a/tests/http-server.test.ts +++ b/tests/http-server.test.ts @@ -4,9 +4,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; +import { CallToolResultSchema } from "@modelcontextprotocol/core"; +import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { afterEach, describe, expect, it } from "vitest"; import { startMiftahHttpServer } from "../src/http/miftah-http-server.js"; import { createHttpSessionRuntime } from "../src/runtime/create-miftah-runtime.js"; diff --git a/tests/mcp-v2-migration-contract.test.ts b/tests/mcp-v2-migration-contract.test.ts new file mode 100644 index 00000000..ac9df63a --- /dev/null +++ b/tests/mcp-v2-migration-contract.test.ts @@ -0,0 +1,28 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +interface PackageManifest { + readonly dependencies?: Readonly>; + readonly devDependencies?: Readonly>; +} + +describe("MCP TypeScript SDK v2 migration contract", () => { + it("ships only the stable split SDK packages required by Miftah", async () => { + const manifest = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")) as PackageManifest; + const dependencies = manifest.dependencies ?? {}; + + expect(dependencies).not.toHaveProperty("@modelcontextprotocol/sdk"); + expect(dependencies).toMatchObject({ + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0", + zod: "^4.2.0" + }); + expect(manifest.devDependencies).toMatchObject({ + "@hono/node-server": "2.0.10", + "@modelcontextprotocol/node": "^2.0.0", + hono: "4.12.34" + }); + }); +}); diff --git a/tests/mcp-v2-serving.test.ts b/tests/mcp-v2-serving.test.ts new file mode 100644 index 00000000..e68b8c5c --- /dev/null +++ b/tests/mcp-v2-serving.test.ts @@ -0,0 +1,158 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { fileURLToPath } from "node:url"; +import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; +import { InMemoryTransport } from "@modelcontextprotocol/server"; +import { serveStdio } from "@modelcontextprotocol/server/stdio"; +import { afterEach, describe, expect, it } from "vitest"; +import { startMiftahHttpServer, type MiftahHttpServer } from "../src/http/miftah-http-server.js"; +import { createMiftahServerFactory } from "../src/runtime/create-miftah-runtime.js"; +import { startFakeRemoteUpstream, type FakeRemoteUpstream } from "./helpers/fake-remote-upstream.js"; + +const fixture = fileURLToPath(new URL("./fixtures/fake-upstream.mjs", import.meta.url)); +const temporaryDirectories: string[] = []; +const httpServers: MiftahHttpServer[] = []; +const remoteUpstreams: FakeRemoteUpstream[] = []; + +afterEach(async () => { + await Promise.all(httpServers.splice(0).map((server) => server.close())); + await Promise.all(remoteUpstreams.splice(0).map((upstream) => upstream.close())); + await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))); +}); + +async function configPath(upstream?: { readonly url: string }): Promise { + const directory = await mkdtemp(join(tmpdir(), "miftah-v2-serving-")); + temporaryDirectories.push(directory); + const path = join(directory, "miftah.json"); + await writeFile( + path, + JSON.stringify({ + version: "1", + name: "v2-serving-test", + defaultProfile: "work", + upstream: upstream === undefined + ? { transport: "stdio", command: process.execPath, args: [fixture] } + : { transport: "streamable-http", url: upstream.url }, + profiles: { work: {} }, + server: { http: { port: 0, maxSessions: 4, sessionIdleTimeoutMs: 1_000 } } + }) + ); + return path; +} + +async function waitFor(condition: () => boolean, timeoutMs = 4_000): Promise { + const deadline = Date.now() + timeoutMs; + while (!condition()) { + if (Date.now() >= deadline) throw new Error("Timed out waiting for the protocol condition."); + await delay(25); + } +} + +describe("MCP SDK v2 serving interoperability", () => { + it("negotiates modern Streamable HTTP without initialize or a session id", async () => { + const server = await startMiftahHttpServer(await configPath()); + httpServers.push(server); + const transport = new StreamableHTTPClientTransport(server.url); + const client = new Client( + { name: "miftah-modern-http-test", version: "1.0.0" }, + { versionNegotiation: { mode: "auto" } } + ); + + try { + await client.connect(transport); + expect(transport.protocolVersion).toBe("2026-07-28"); + expect(transport.sessionId).toBeUndefined(); + expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); + expect(transport.sessionId).toBeUndefined(); + } finally { + await client.close(); + } + }); + + it("preserves the legacy initialized Streamable HTTP session path", async () => { + const server = await startMiftahHttpServer(await configPath()); + httpServers.push(server); + const transport = new StreamableHTTPClientTransport(server.url); + const client = new Client({ name: "miftah-legacy-http-test", version: "1.0.0" }); + + try { + await client.connect(transport); + expect(transport.protocolVersion).toBe("2025-11-25"); + expect(transport.sessionId).toEqual(expect.any(String)); + expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); + } finally { + await client.close(); + } + }); + + it.each([ + ["modern", { versionNegotiation: { mode: "auto" as const } }, "modern"], + ["legacy", undefined, "legacy"] + ])("serves %s clients through the SDK v2 stdio entry", async (_era, clientOptions, expectedEra) => { + const path = await configPath(); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const baseFactory = createMiftahServerFactory(path); + const eras: string[] = []; + const handle = serveStdio((context) => { + eras.push(context.era); + return baseFactory(context); + }, { transport: serverTransport }); + const client = new Client( + { name: `miftah-${_era}-stdio-test`, version: "1.0.0" }, + clientOptions + ); + + try { + await client.connect(clientTransport); + expect([...new Set(eras)]).toEqual([expectedEra]); + expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); + } finally { + await client.close(); + await handle.close(); + } + }); + + it("returns an explicit supported-version diagnostic for a pinned unsupported revision", async () => { + const server = await startMiftahHttpServer(await configPath()); + httpServers.push(server); + const transport = new StreamableHTTPClientTransport(server.url); + const client = new Client( + { name: "miftah-unsupported-http-test", version: "1.0.0" }, + { versionNegotiation: { mode: { pin: "2099-01-01" } } } + ); + + try { + await expect(client.connect(transport)).rejects.toMatchObject({ + data: { requested: "2099-01-01", supported: ["2026-07-28"] } + }); + } finally { + await client.close(); + } + }); + + it("propagates modern HTTP request cancellation to the selected upstream", async () => { + const upstream = await startFakeRemoteUpstream({ callToolDelayMs: 5_000 }); + remoteUpstreams.push(upstream); + const server = await startMiftahHttpServer(await configPath({ url: upstream.streamableHttpUrl })); + httpServers.push(server); + const transport = new StreamableHTTPClientTransport(server.url); + const client = new Client( + { name: "miftah-modern-http-cancellation-test", version: "1.0.0" }, + { versionNegotiation: { mode: "auto" } } + ); + + try { + await client.connect(transport); + const controller = new AbortController(); + const pending = client.callTool({ name: "whoami", arguments: {} }, { signal: controller.signal }); + await waitFor(() => upstream.toolCallRequests() === 1); + controller.abort(); + await expect(pending).rejects.toBeDefined(); + await waitFor(() => upstream.cancelledNotifications() === 1); + } finally { + await client.close(); + } + }); +}); diff --git a/tests/mcp-wrapper.test.ts b/tests/mcp-wrapper.test.ts index f7654a61..c2d35ebf 100644 --- a/tests/mcp-wrapper.test.ts +++ b/tests/mcp-wrapper.test.ts @@ -1,19 +1,8 @@ -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import type { Transport, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js"; +import { CallToolResultSchema, RootsListChangedNotificationSchema } from "@modelcontextprotocol/core"; +import { InMemoryTransport, Client, UriTemplate } from "@modelcontextprotocol/client"; +import type { Transport, TransportSendOptions, JSONRPCMessage } from "@modelcontextprotocol/client"; import { randomUUID } from "node:crypto"; import { setTimeout as delay } from "node:timers/promises"; -import { - CallToolResultSchema, - ListRootsRequestSchema, - PromptListChangedNotificationSchema, - ResourceListChangedNotificationSchema, - ResourceUpdatedNotificationSchema, - RootsListChangedNotificationSchema, - ToolListChangedNotificationSchema -} from "@modelcontextprotocol/sdk/types.js"; -import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -855,8 +844,7 @@ describe("Miftah MCP wrapper", () => { await client.callTool({ name: "miftah_verify_identity", arguments: { profile: "work" } }); const profilesResult = await client.callTool( - { name: "miftah_list_profiles", arguments: {} }, - CallToolResultSchema + { name: "miftah_list_profiles", arguments: {} } ); if (!Array.isArray(profilesResult.content)) throw new Error("Expected profile list content."); const profilesContent = profilesResult.content[0]; @@ -1925,7 +1913,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "test-client", version: "1.0.0" }); let notifications = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { notifications += 1; }); @@ -1972,7 +1960,7 @@ describe("Miftah MCP wrapper", () => { try { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); - const pending = client.callTool({ name: "whoami", arguments: {} }, undefined, { signal: controller.signal }); + const pending = client.callTool({ name: "whoami", arguments: {} }, { signal: controller.signal }); await expect.poll(async () => access(startedPath).then(() => true, () => false)).toBe(true); controller.abort("test cancellation"); @@ -2087,7 +2075,6 @@ describe("Miftah MCP wrapper", () => { toolListStarted = watchForPathArrival(startedPath); const pending = client.callTool( { name: "miftah_list_upstream_tools", arguments: {} }, - undefined, { signal: controller.signal } ); await Promise.race([ @@ -2336,7 +2323,6 @@ describe("Miftah MCP wrapper", () => { expect( await client.callTool( { name: "whoami", arguments: {} }, - undefined, { onprogress: (progress) => progressUpdates.push(progress) } ) ).toMatchObject({ content: [{ type: "text", text: "work" }] }); @@ -2505,7 +2491,7 @@ describe("Miftah MCP wrapper", () => { try { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); - await expect(client.listResourceTemplates()).rejects.toThrow(/^MCP error -32603: RESOURCE_TEMPLATES_UNAVAILABLE:/); + await expect(client.listResourceTemplates()).rejects.toThrow(/^RESOURCE_TEMPLATES_UNAVAILABLE:/); } finally { await client.close(); await wrapper.close(); @@ -2538,7 +2524,7 @@ describe("Miftah MCP wrapper", () => { try { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); - await expect(client.listResourceTemplates()).rejects.toThrow(/^MCP error -32603: RESOURCE_TEMPLATES_UNAVAILABLE:/); + await expect(client.listResourceTemplates()).rejects.toThrow(/^RESOURCE_TEMPLATES_UNAVAILABLE:/); } finally { await client.close(); await wrapper.close(); @@ -2586,7 +2572,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "resource-subscription-test-client", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -2633,7 +2619,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "resource-subscription-filter-test", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -2671,7 +2657,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "failed-resource-subscription-test-client", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -2717,7 +2703,7 @@ describe("Miftah MCP wrapper", () => { const client = new Client({ name: "cancelled-resource-subscription-test-client", version: "1.0.0" }); const controller = new AbortController(); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -2879,7 +2865,7 @@ describe("Miftah MCP wrapper", () => { const controller = new AbortController(); const updates: string[] = []; let subscribeStarted: PathArrivalWatch | undefined; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -2938,7 +2924,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "resource-subscription-fanout-test-client", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -3251,7 +3237,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "resource-subscription-pre-candidate-switch-test", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -3300,7 +3286,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "resource-subscription-idle-test", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -3338,7 +3324,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "resource-subscription-switch-test", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -3386,7 +3372,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "resource-subscription-third-profile-test", version: "1.0.0" }); const updates: string[] = []; - client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + client.setNotificationHandler('notifications/resources/updated', (notification) => { updates.push(notification.params.uri); }); @@ -3624,13 +3610,13 @@ describe("Miftah MCP wrapper", () => { let toolsChanged = 0; let resourcesChanged = 0; let promptsChanged = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { toolsChanged += 1; }); - client.setNotificationHandler(ResourceListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/resources/list_changed', () => { resourcesChanged += 1; }); - client.setNotificationHandler(PromptListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/prompts/list_changed', () => { promptsChanged += 1; }); @@ -3671,7 +3657,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "tool-discovery-list-change-test", version: "1.0.0" }); let changes = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { changes += 1; }); @@ -3710,7 +3696,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "initial-tool-list-change-refresh-test", version: "1.0.0" }); let changes = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { changes += 1; }); @@ -3788,7 +3774,7 @@ describe("Miftah MCP wrapper", () => { const toolListChanged = new Promise((resolve) => { notifyToolListChanged = resolve; }); - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { notifyToolListChanged?.(); }); @@ -3830,7 +3816,7 @@ describe("Miftah MCP wrapper", () => { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); const result = CallToolResultSchema.parse( - await client.callTool({ name: "miftah_current_profile", arguments: {} }, CallToolResultSchema) + await client.callTool({ name: "miftah_current_profile", arguments: {} }) ); const content = result.content[0]; expect(content).toMatchObject({ type: "text" }); @@ -4284,7 +4270,7 @@ describe("Miftah MCP wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "test-client", version: "1.0.0" }); let notifications = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { notifications += 1; }); @@ -4439,7 +4425,7 @@ describe("Miftah MCP wrapper", () => { { capabilities: { roots: { listChanged: true } } } ); let rootRequests = 0; - client.setRequestHandler(ListRootsRequestSchema, async () => { + client.setRequestHandler('roots/list', async () => { rootRequests += 1; return { roots: [{ uri: fixture.matchingRoot, name: "matching", _meta: { ignored: true } }] @@ -4475,7 +4461,7 @@ describe("Miftah MCP wrapper", () => { { capabilities: { roots: { listChanged: true } } } ); let rootRequests = 0; - client.setRequestHandler(ListRootsRequestSchema, async () => { + client.setRequestHandler('roots/list', async () => { rootRequests += 1; return { roots: [{ uri: fixture.matchingRoot }] }; }); @@ -4489,7 +4475,7 @@ describe("Miftah MCP wrapper", () => { expect(client.getServerCapabilities()).toMatchObject({ tools: { listChanged: true } }); expect(rootRequests).toBe(0); expect( - await client.callTool({ name: "whoami", arguments: {} }, CallToolResultSchema, { timeout: 500 }) + await client.callTool({ name: "whoami", arguments: {} }, { timeout: 500 }) ).toMatchObject({ content: [{ type: "text", text: "work" }] }); expect(rootRequests).toBe(0); } finally { @@ -4534,7 +4520,7 @@ describe("Miftah MCP wrapper", () => { { name: "relative-runtime-config-client", version: "1.0.0" }, { capabilities: { roots: {} } } ); - client.setRequestHandler(ListRootsRequestSchema, async () => ({ + client.setRequestHandler('roots/list', async () => ({ roots: [{ uri: pathToFileURL(projectDirectory).toString() }] })); @@ -4556,18 +4542,10 @@ describe("Miftah MCP wrapper", () => { const routingFixture = await createRuntimeRoutingFixture(); const runtime = await createMiftahRuntime(routingFixture.configPath); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const capabilities: { roots?: Record } = { roots: {} }; const client = new Client( { name: "roots-disabled-client", version: "1.0.0" }, - { capabilities } + { capabilities: {} } ); - let rootRequests = 0; - client.setRequestHandler(ListRootsRequestSchema, async () => { - rootRequests += 1; - return { roots: [] }; - }); - delete capabilities.roots; - const config = validateConfig({ version: "1", name: "accounts", @@ -4583,7 +4561,7 @@ describe("Miftah MCP wrapper", () => { { capabilities: { roots: { listChanged: true } } } ); let directRootRequests = 0; - directClient.setRequestHandler(ListRootsRequestSchema, async () => { + directClient.setRequestHandler('roots/list', async () => { directRootRequests += 1; return { roots: [] }; }); @@ -4593,8 +4571,6 @@ describe("Miftah MCP wrapper", () => { expect(await client.callTool({ name: "whoami", arguments: {} })).toMatchObject({ content: [{ type: "text", text: "work" }] }); - expect(rootRequests).toBe(0); - await Promise.all([wrapper.connect(directServerTransport), directClient.connect(directClientTransport)]); expect(await directClient.callTool({ name: "whoami", arguments: {} })).toMatchObject({ content: [{ type: "text", text: "work" }] @@ -4620,7 +4596,7 @@ describe("Miftah MCP wrapper", () => { { capabilities: { roots: { listChanged: true } } } ); let rootRequests = 0; - client.setRequestHandler(ListRootsRequestSchema, async () => { + client.setRequestHandler('roots/list', async () => { rootRequests += 1; throw new Error("roots unavailable"); }); @@ -4654,7 +4630,7 @@ describe("Miftah MCP wrapper", () => { ); let currentRoot = fixture.matchingRoot; let rootRequests = 0; - client.setRequestHandler(ListRootsRequestSchema, async () => { + client.setRequestHandler('roots/list', async () => { rootRequests += 1; return { roots: [{ uri: currentRoot }] }; }); @@ -4668,7 +4644,7 @@ describe("Miftah MCP wrapper", () => { ); let unchangedRoot = unchangedFixture.matchingRoot; let unchangedRootRequests = 0; - unchangedClient.setRequestHandler(ListRootsRequestSchema, async () => { + unchangedClient.setRequestHandler('roots/list', async () => { unchangedRootRequests += 1; return { roots: [{ uri: unchangedRoot }] }; }); @@ -4735,7 +4711,7 @@ describe("Miftah MCP wrapper", () => { }); let rootRequests = 0; let currentRoot = fixture.matchingRoot; - client.setRequestHandler(ListRootsRequestSchema, async () => { + client.setRequestHandler('roots/list', async () => { rootRequests += 1; const responseRoot = currentRoot; if (rootRequests === 1) { diff --git a/tests/multi-upstream.test.ts b/tests/multi-upstream.test.ts index af39461b..56ec5c06 100644 --- a/tests/multi-upstream.test.ts +++ b/tests/multi-upstream.test.ts @@ -1,15 +1,11 @@ -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { CallToolResultSchema, GetPromptResultSchema, ListPromptsResultSchema, ListResourcesResultSchema, - PromptListChangedNotificationSchema, - ReadResourceResultSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema -} from "@modelcontextprotocol/sdk/types.js"; + ReadResourceResultSchema +} from "@modelcontextprotocol/core"; +import { InMemoryTransport, Client } from "@modelcontextprotocol/client"; import { access, mkdtemp, readFile, unlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -33,6 +29,14 @@ const githubResourceRoutePattern = /^miftah:\/\/resource\/github\?/; const resourceNotFoundPattern = /RESOURCE_NOT_FOUND/; const promptNotFoundPattern = /PROMPT_NOT_FOUND/; +function listResourcesPage(client: Client, cursor?: string) { + return client.request({ method: "resources/list", params: cursor === undefined ? {} : { cursor } }); +} + +function listPromptsPage(client: Client, cursor?: string) { + return client.request({ method: "prompts/list", params: cursor === undefined ? {} : { cursor } }); +} + describe("multi-upstream wrapper", () => { it("does not proxy resources or prompts when no upstream is configured", async () => { const config = validateConfig({ @@ -70,7 +74,7 @@ describe("multi-upstream wrapper", () => { await expect(client.request(request, resultSchema)).rejects.toMatchObject({ code: -32601 }); } - const health = await client.callTool({ name: "miftah_health", arguments: {} }, CallToolResultSchema); + const health = await client.callTool({ name: "miftah_health", arguments: {} }); const text = CallToolResultSchema.parse(health).content[0]; expect(text?.type).toBe("text"); if (text?.type !== "text") throw new Error("Expected a text health result"); @@ -118,7 +122,7 @@ describe("multi-upstream wrapper", () => { expect(client.getServerCapabilities()).toMatchObject({ resources: {}, prompts: {} }); expect(client.getInstructions()).not.toContain("multi-upstream"); - const health = await client.callTool({ name: "miftah_health", arguments: {} }, CallToolResultSchema); + const health = await client.callTool({ name: "miftah_health", arguments: {} }); const text = CallToolResultSchema.parse(health).content[0]; expect(text?.type).toBe("text"); if (text?.type !== "text") throw new Error("Expected a text health result"); @@ -170,7 +174,7 @@ describe("multi-upstream wrapper", () => { expect((await client.listPrompts()).prompts.map((prompt) => prompt.name)).toEqual(["github__account_prompt"]); const health = CallToolResultSchema.parse( - await client.callTool({ name: "miftah_health", arguments: {} }, CallToolResultSchema) + await client.callTool({ name: "miftah_health", arguments: {} }) ); const content = health.content[0]; expect(content).toMatchObject({ type: "text" }); @@ -240,7 +244,7 @@ describe("multi-upstream wrapper", () => { "github__Current account" ]); const health = CallToolResultSchema.parse( - await client.callTool({ name: "miftah_health", arguments: {} }, CallToolResultSchema) + await client.callTool({ name: "miftah_health", arguments: {} }) ); const content = health.content[0]; expect(content).toMatchObject({ type: "text" }); @@ -588,10 +592,10 @@ describe("multi-upstream wrapper", () => { const client = new Client({ name: "test-client", version: "1.0.0" }); let resourceNotifications = 0; let promptNotifications = 0; - client.setNotificationHandler(ResourceListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/resources/list_changed', () => { resourceNotifications += 1; }); - client.setNotificationHandler(PromptListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/prompts/list_changed', () => { promptNotifications += 1; }); @@ -699,7 +703,7 @@ describe("multi-upstream wrapper", () => { try { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); - const firstResources = await client.listResources(); + const firstResources = await listResourcesPage(client); expect(firstResources.resources.map((resource) => resource.name)).toEqual([ "github__Current account", "sentry__Current account" @@ -715,7 +719,7 @@ describe("multi-upstream wrapper", () => { ]); expect(secondResources.nextCursor).toBeUndefined(); - const firstPrompts = await client.listPrompts(); + const firstPrompts = await listPromptsPage(client); expect(firstPrompts.prompts.map((prompt) => prompt.name)).toEqual([ "github__account_prompt", "sentry__account_prompt" @@ -766,10 +770,10 @@ describe("multi-upstream wrapper", () => { const client = new Client({ name: "test-client", version: "1.0.0" }); let resourceNotifications = 0; let promptNotifications = 0; - client.setNotificationHandler(ResourceListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/resources/list_changed', () => { resourceNotifications += 1; }); - client.setNotificationHandler(PromptListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/prompts/list_changed', () => { promptNotifications += 1; }); @@ -780,8 +784,8 @@ describe("multi-upstream wrapper", () => { resources: { listChanged: true }, prompts: { listChanged: true } }); - const workResources = await client.listResources(); - const workPrompts = await client.listPrompts(); + const workResources = await listResourcesPage(client); + const workPrompts = await listPromptsPage(client); if (!workResources.nextCursor || !workPrompts.nextCursor) { throw new Error("Expected work-profile aggregate cursors."); } @@ -985,7 +989,7 @@ describe("multi-upstream wrapper", () => { await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); expect(client.getServerCapabilities()).toMatchObject({ resources: {}, prompts: {} }); - const firstResources = await client.listResources(); + const firstResources = await listResourcesPage(client); expect(firstResources).toMatchObject({ resources: [{ uri: "account://current" }], nextCursor: "next" @@ -996,7 +1000,7 @@ describe("multi-upstream wrapper", () => { expect(await client.readResource({ uri: "account://current" })).toMatchObject({ contents: [{ text: "github-work" }] }); - const firstPrompts = await client.listPrompts(); + const firstPrompts = await listPromptsPage(client); expect(firstPrompts).toMatchObject({ prompts: [{ name: "account_prompt" }], nextCursor: "next" @@ -1215,13 +1219,13 @@ describe("multi-upstream wrapper", () => { let notifications = 0; let resourceNotifications = 0; let promptNotifications = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { notifications += 1; }); - client.setNotificationHandler(ResourceListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/resources/list_changed', () => { resourceNotifications += 1; }); - client.setNotificationHandler(PromptListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/prompts/list_changed', () => { promptNotifications += 1; }); @@ -1234,7 +1238,7 @@ describe("multi-upstream wrapper", () => { expect(beforePids.every((pid): pid is number => typeof pid === "number")).toBe(true); const restarted = CallToolResultSchema.parse( - await client.callTool({ name: "miftah_restart_profile", arguments: { profile: "work" } }, CallToolResultSchema) + await client.callTool({ name: "miftah_restart_profile", arguments: { profile: "work" } }) ); expect(restarted.isError).not.toBe(true); await client.listTools(); @@ -1284,7 +1288,7 @@ describe("multi-upstream wrapper", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "test-client", version: "1.0.0" }); let notifications = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { notifications += 1; }); @@ -1293,7 +1297,7 @@ describe("multi-upstream wrapper", () => { await client.listTools(); const restarted = CallToolResultSchema.parse( - await client.callTool({ name: "miftah_restart_profile", arguments: { profile: "work" } }, CallToolResultSchema) + await client.callTool({ name: "miftah_restart_profile", arguments: { profile: "work" } }) ); expect(restarted.isError).toBe(true); const partial = await client.listTools(); @@ -1348,13 +1352,13 @@ describe("multi-upstream wrapper", () => { let notifications = 0; let resourceNotifications = 0; let promptNotifications = 0; - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/tools/list_changed', () => { notifications += 1; }); - client.setNotificationHandler(ResourceListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/resources/list_changed', () => { resourceNotifications += 1; }); - client.setNotificationHandler(PromptListChangedNotificationSchema, () => { + client.setNotificationHandler('notifications/prompts/list_changed', () => { promptNotifications += 1; }); @@ -1468,8 +1472,7 @@ describe("multi-upstream wrapper", () => { countFixtureStarts(sentryStartCountPath) ]); const restart = client.callTool( - { name: "miftah_restart_profile", arguments: { profile: "work" } }, - CallToolResultSchema + { name: "miftah_restart_profile", arguments: { profile: "work" } } ); try { await expect diff --git a/tests/oauth-loopback-handoff.test.ts b/tests/oauth-loopback-handoff.test.ts index 4fd98169..de900ae6 100644 --- a/tests/oauth-loopback-handoff.test.ts +++ b/tests/oauth-loopback-handoff.test.ts @@ -45,7 +45,10 @@ describe("OAuth loopback authorization handoff", () => { const acceptedResponse = await fetch(callback); const page = await acceptedResponse.text(); - await expect(code).resolves.toBe("fixture-authorization-code"); + await expect(code).resolves.toEqual({ + authorizationCode: "fixture-authorization-code", + issuer: "https://issuer.example.test" + }); expect(acceptedResponse.status).toBe(200); expect(page).not.toContain("fixture-authorization-code"); expect(page).not.toContain("fixture-state-value-that-is-long-enough"); @@ -80,7 +83,7 @@ describe("OAuth loopback authorization handoff", () => { callback.searchParams.set("state", state); callback.searchParams.set("iss", issuer); expect((await fetch(callback)).status).toBe(200); - await expect(code).resolves.toBe("accepted-code"); + await expect(code).resolves.toEqual({ authorizationCode: "accepted-code", issuer }); } finally { await handoff.close(); } diff --git a/tests/operation-pipeline.test.ts b/tests/operation-pipeline.test.ts index a2a8ef21..f71400c9 100644 --- a/tests/operation-pipeline.test.ts +++ b/tests/operation-pipeline.test.ts @@ -1,5 +1,4 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { access, mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; diff --git a/tests/package-contract.test.ts b/tests/package-contract.test.ts index 60418358..90b08671 100644 --- a/tests/package-contract.test.ts +++ b/tests/package-contract.test.ts @@ -13,6 +13,7 @@ interface PackageManifest { name?: string; version?: string; dependencies?: Record; + devDependencies?: Record; repository?: unknown; homepage?: unknown; bugs?: unknown; @@ -65,6 +66,7 @@ const publicRuntimeExports = [ "ProfileContextHandleService", "createAuthenticatedRequestContextBoundary", "createMiftahRuntime", + "createMiftahServerFactory", "generateConfigSchema", "loadConfig", "presetConfig", @@ -80,6 +82,9 @@ const requiredPackPaths = [ "dist/plugin-api.d.ts", "dist/plugin-api.js", "dist/plugin-host.js", + "dist/third-party/hono-node-server.LICENSE", + "dist/third-party/hono.LICENSE", + "dist/third-party/modelcontextprotocol-node.LICENSE", "dist/windows-secret-job.exe", "docs/cli.md", "docs/library-api.md", @@ -113,7 +118,6 @@ function assertPatchedFastUriLockEntries(lock: PackageLock): void { ([packagePath]) => packagePath === suffix || packagePath.endsWith(`/${suffix}`) ); - expect(entries, "fast-uri must exist in the package lock").not.toHaveLength(0); for (const [packagePath, packageEntry] of entries) { expect(packageEntry["version"], `${packagePath} must resolve to the patched release`).toBe("3.1.5"); } @@ -761,7 +765,7 @@ describe("package metadata contract", () => { assertPatchedEsbuildLockEntries(lock); }); - it("locks the patched fast-uri release for GHSA-7p8r-x3mc-p8w7", () => { + it("locks any retained fast-uri resolution to the patched release for GHSA-7p8r-x3mc-p8w7", () => { const manifest = readPackageManifest(); const lock = JSON.parse(readFileSync(new URL("../package-lock.json", import.meta.url), "utf8")) as PackageLock; @@ -772,24 +776,37 @@ describe("package metadata contract", () => { it("locks the patched transitive security releases tracked by #373", () => { const manifest = readPackageManifest(); const lock = JSON.parse(readFileSync(new URL("../package-lock.json", import.meta.url), "utf8")) as PackageLock; - const expectedVersions = { + const expectedOverrides = { "brace-expansion": "5.0.9", - hono: "4.12.34", "ip-address": "10.3.1", nanoid: "3.3.17" } as const; - for (const [packageName, expectedVersion] of Object.entries(expectedVersions)) { + for (const [packageName, expectedVersion] of Object.entries(expectedOverrides)) { expect(manifest.overrides?.[packageName]).toBe(expectedVersion); assertPatchedTransitiveLockEntries(lock, packageName, expectedVersion); } + expect(manifest.devDependencies?.hono).toBe("4.12.34"); + expect(manifest.overrides).not.toHaveProperty("hono"); + assertPatchedTransitiveLockEntries(lock, "hono", "4.12.34"); }); it("locks the patched MCP SDK and Hono Node server releases for GHSA-frvp-7c67-39w9", () => { const manifest = readPackageManifest(); const lock = JSON.parse(readFileSync(new URL("../package-lock.json", import.meta.url), "utf8")) as PackageLock; - expect(manifest.dependencies?.["@modelcontextprotocol/sdk"]).toBe("^1.30.0"); + expect(manifest.dependencies).not.toHaveProperty("@modelcontextprotocol/sdk"); + expect(manifest.dependencies).toMatchObject({ + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0" + }); + expect(manifest.devDependencies).toMatchObject({ + "@hono/node-server": "2.0.10", + "@modelcontextprotocol/node": "^2.0.0", + hono: "4.12.34" + }); expect(manifest.overrides?.["@hono/node-server"]).toBe("2.0.10"); assertPatchedHonoNodeServerLockEntries(lock); }); @@ -838,12 +855,12 @@ describe("package metadata contract", () => { const lock: PackageLock = { packages: { "node_modules/@hono/node-server": { version: "2.0.10" }, - "node_modules/@modelcontextprotocol/sdk/node_modules/@hono/node-server": { version: "1.19.9" } + "node_modules/@modelcontextprotocol/node/node_modules/@hono/node-server": { version: "1.19.9" } } }; expect(() => assertPatchedHonoNodeServerLockEntries(lock)).toThrow( - /node_modules\/@modelcontextprotocol\/sdk\/node_modules\/@hono\/node-server/ + /node_modules\/@modelcontextprotocol\/node\/node_modules\/@hono\/node-server/ ); }); }); @@ -1078,6 +1095,9 @@ describe("packed artifact contract", () => { await readFile(join(directory, "node_modules", "@lubab", "miftah", "package.json"), "utf8") ) as PackageManifest; expect(installedManifest.dependencies).toEqual(readPackageManifest().dependencies); + expect(existsSync(join(directory, "node_modules", "@modelcontextprotocol", "node"))).toBe(false); + expect(existsSync(join(directory, "node_modules", "@hono", "node-server"))).toBe(false); + expect(existsSync(join(directory, "node_modules", "hono"))).toBe(false); const consumerPath = join(directory, "consumer.mjs"); const configPath = join(directory, "miftah.json"); @@ -1102,8 +1122,8 @@ describe("packed artifact contract", () => { [ 'import * as api from "@lubab/miftah";', 'import * as pluginApi from "@lubab/miftah/plugin-api";', - 'import { Client } from "@modelcontextprotocol/sdk/client/index.js";', - 'import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";', + 'import { Client } from "@modelcontextprotocol/client";', + 'import { InMemoryTransport } from "@modelcontextprotocol/server";', 'import { readFile } from "node:fs/promises";', "", "const runtime = await api.createMiftahRuntime(process.argv[2]);", @@ -1230,7 +1250,7 @@ describe("packed artifact contract", () => { await writeFile( typeConsumerPath, [ - 'import { AuthenticatedRequestContextError, InMemoryProfileContextRevocationStore, PROFILE_CONTEXT_ARGUMENT, PROFILE_CONTEXT_META_KEY, ProfileContextHandleError, ProfileContextHandleService, createAuthenticatedRequestContextBoundary, createMiftahRuntime, requireAuthenticatedRequestContext, CURRENT_CONFIG_VERSION, MIFTAH_VERSION, type ActiveProfileStateScope, type AuthenticatedRequestContext, type AuthenticatedRequestContextBoundary, type AuthenticatedRequestContextBoundaryOptions, type AuthenticatedRequestContextErrorCode, type AuditConfig, type AuditIntegrityConfig, type AuditRotationConfig, type ConfigDiagnostic, type GitHubProfileRoutingMatch, type IdentityConfig, type IdentityFingerprint, type IdentityProbeConfig, type JiraProfileRoutingMatch, type LinearProfileRoutingMatch, type MiftahConfig, type MiftahConfigVersion, type MiftahErrorCode, type MiftahErrorDetails, type MiftahRuntime, type MiftahRuntimeOptions, type MintedProfileContext, type ModernProfileContextRuntimeOptions, type PluginConfig, type PluginKind, type PluginsConfig, type PolicyConfig, type PostHogProfileRoutingMatch, type ProcessConfig, type ProfileConfig, type ProfileContextHandleErrorCode, type ProfileContextHandleServiceOptions, type ProfileContextKeyEpoch, type ProfileContextKeyringProvider, type ProfileContextKeyringSnapshot, type ProfileContextReplacementAudit, type ProfileContextRevocationStore, type ProfileIsolationConfig, type ProfileIsolationContainerVolume, type ProfileIsolationFile, type ProfileLeaseConfig, type ProfileRoutingConfig, type ProfileRoutingMatchConfig, type ProfileUpstreamOverride, type ResolvedProfileContext, type RiskLevel, type RoutingConfig, type RoutingMatcherPluginConfig, type RoutingRule, type SecurityConfig, type SentryProfileRoutingMatch, type SecretProviderPluginConfig, type StateConfig, type ToolDiscoveryMode, type ToolingConfig, type TransportType, type UnknownToolRisk, type UpstreamConfig, type ValidatedRoutingConfig, type VerifiedHttpRequestClaims, type VerifiedHttpRequestClaimsProvider } from "@lubab/miftah";', + 'import { AuthenticatedRequestContextError, InMemoryProfileContextRevocationStore, PROFILE_CONTEXT_ARGUMENT, PROFILE_CONTEXT_META_KEY, ProfileContextHandleError, ProfileContextHandleService, createAuthenticatedRequestContextBoundary, createMiftahRuntime, createMiftahServerFactory, requireAuthenticatedRequestContext, CURRENT_CONFIG_VERSION, MIFTAH_VERSION, type ActiveProfileStateScope, type AuthenticatedRequestContext, type AuthenticatedRequestContextBoundary, type AuthenticatedRequestContextBoundaryOptions, type AuthenticatedRequestContextErrorCode, type AuditConfig, type AuditIntegrityConfig, type AuditRotationConfig, type ConfigDiagnostic, type GitHubProfileRoutingMatch, type IdentityConfig, type IdentityFingerprint, type IdentityProbeConfig, type JiraProfileRoutingMatch, type LinearProfileRoutingMatch, type MiftahConfig, type MiftahConfigVersion, type MiftahErrorCode, type MiftahErrorDetails, type MiftahRuntime, type MiftahRuntimeOptions, type MintedProfileContext, type ModernProfileContextRuntimeOptions, type PluginConfig, type PluginKind, type PluginsConfig, type PolicyConfig, type PostHogProfileRoutingMatch, type ProcessConfig, type ProfileConfig, type ProfileContextHandleErrorCode, type ProfileContextHandleServiceOptions, type ProfileContextKeyEpoch, type ProfileContextKeyringProvider, type ProfileContextKeyringSnapshot, type ProfileContextReplacementAudit, type ProfileContextRevocationStore, type ProfileIsolationConfig, type ProfileIsolationContainerVolume, type ProfileIsolationFile, type ProfileLeaseConfig, type ProfileRoutingConfig, type ProfileRoutingMatchConfig, type ProfileUpstreamOverride, type ResolvedProfileContext, type RiskLevel, type RoutingConfig, type RoutingMatcherPluginConfig, type RoutingRule, type SecurityConfig, type SentryProfileRoutingMatch, type SecretProviderPluginConfig, type StateConfig, type ToolDiscoveryMode, type ToolingConfig, type TransportType, type UnknownToolRisk, type UpstreamConfig, type ValidatedRoutingConfig, type VerifiedHttpRequestClaims, type VerifiedHttpRequestClaimsProvider } from "@lubab/miftah";', 'import { MIFTAH_PLUGIN_API_VERSION, type MiftahPlugin, type RoutingMatcherPlugin, type RoutingMatcherPluginRequest, type RoutingMatcherPluginResult, type RoutingMatcherPluginSignal, type SecretProviderPlugin, type SecretProviderPluginRequest, type SecretProviderPluginResult } from "@lubab/miftah/plugin-api";', "", "type SupportedTypes = [", @@ -1245,6 +1265,7 @@ describe("packed artifact contract", () => { "const version: string = MIFTAH_VERSION;", 'const pluginApiVersion: "1" = MIFTAH_PLUGIN_API_VERSION;', 'const runtime: Promise = createMiftahRuntime("./miftah.json");', + 'const serverFactory = createMiftahServerFactory("./miftah.json");', 'const authError: AuthenticatedRequestContextError = new AuthenticatedRequestContextError("AUTH_CONTEXT_UNAVAILABLE");', 'const profileContextError: ProfileContextHandleError = new ProfileContextHandleError("PROFILE_CONTEXT_UNAVAILABLE");', "const profileContextArgument: string = PROFILE_CONTEXT_ARGUMENT;", diff --git a/tests/plugin-routing-server.test.ts b/tests/plugin-routing-server.test.ts index 401dde71..4d8615fa 100644 --- a/tests/plugin-routing-server.test.ts +++ b/tests/plugin-routing-server.test.ts @@ -1,5 +1,4 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; diff --git a/tests/profile-context-handle-docs-contract.test.ts b/tests/profile-context-handle-docs-contract.test.ts index 26221834..54475a9f 100644 --- a/tests/profile-context-handle-docs-contract.test.ts +++ b/tests/profile-context-handle-docs-contract.test.ts @@ -16,16 +16,16 @@ describe("profile-context handle documentation contract", () => { expect(documentation).toContain("provide shared revocation storage"); expect(documentation).toContain("strips either form before audit argument capture"); expect(documentation).toContain("is not operation authorization or idempotency"); - expect(documentation).toContain("does not enable this option"); + expect(documentation).toContain("does not enable trusted `modernProfileContext` claims"); }); - it("records the production boundary under the next release without claiming transport negotiation", async () => { + it("records the production boundary alongside protocol negotiation", async () => { const changelog = await readFile(changelogPath, "utf8"); const [, afterUnreleased = ""] = changelog.split(/^## \[Unreleased\]\s*$/mu); const unreleased = afterUnreleased.split(/^## \[/mu, 1)[0] ?? ""; expect(unreleased).toContain("[#377]"); expect(unreleased).toContain("opt-in production profile-context boundary"); - expect(unreleased).toContain("protocol-era negotiation is enabled separately"); + expect(unreleased).toContain("an embedding host enables the boundary through `createMiftahServerFactory`"); }); }); diff --git a/tests/profile-lease-pipeline.test.ts b/tests/profile-lease-pipeline.test.ts index dea92bd5..647b7dab 100644 --- a/tests/profile-lease-pipeline.test.ts +++ b/tests/profile-lease-pipeline.test.ts @@ -1,5 +1,4 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { access, mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; diff --git a/tests/profile-lock-mcp.test.ts b/tests/profile-lock-mcp.test.ts index de961d54..70d78c42 100644 --- a/tests/profile-lock-mcp.test.ts +++ b/tests/profile-lock-mcp.test.ts @@ -1,6 +1,5 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; +import { CallToolResultSchema } from "@modelcontextprotocol/core"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; diff --git a/tests/profile-transition-audit-barrier.test.ts b/tests/profile-transition-audit-barrier.test.ts index ede2f557..10ecb511 100644 --- a/tests/profile-transition-audit-barrier.test.ts +++ b/tests/profile-transition-audit-barrier.test.ts @@ -1,5 +1,4 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { access, mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; diff --git a/tests/progress-preserving-transport.test.ts b/tests/progress-preserving-transport.test.ts index 16509e0b..585ffc2a 100644 --- a/tests/progress-preserving-transport.test.ts +++ b/tests/progress-preserving-transport.test.ts @@ -1,5 +1,4 @@ -import type { Transport, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js"; -import type { JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/sdk/types.js"; +import type { Transport, TransportSendOptions, JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/server"; import { describe, expect, it } from "vitest"; import { ProgressPreservingTransport } from "../src/upstream/progress-preserving-transport.js"; diff --git a/tests/public-api.test.ts b/tests/public-api.test.ts index 32fe76cf..9742d9f8 100644 --- a/tests/public-api.test.ts +++ b/tests/public-api.test.ts @@ -2,8 +2,7 @@ import { readFile, writeFile, mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { describe, expect, it } from "vitest"; import { readFileSync } from "node:fs"; import * as api from "../src/index.js"; @@ -85,6 +84,7 @@ const supportedRuntimeExports = [ "ProfileContextHandleService", "createAuthenticatedRequestContextBoundary", "createMiftahRuntime", + "createMiftahServerFactory", "generateConfigSchema", "loadConfig", "presetConfig", diff --git a/tests/release-config.test.ts b/tests/release-config.test.ts index 0d629c9b..382fdf9b 100644 --- a/tests/release-config.test.ts +++ b/tests/release-config.test.ts @@ -26,6 +26,14 @@ function readPackageOverrides(): Record { return packageJson.overrides; } +function readPackageDevelopmentDependencies(): Record { + const packageJson = JSON.parse(readRepositoryFile("package.json")) as { + devDependencies?: Record; + }; + if (!packageJson.devDependencies) throw new Error("package.json does not define development dependencies."); + return packageJson.devDependencies; +} + function readLockedPackages(): Record { const lockfile = JSON.parse(readRepositoryFile("package-lock.json")) as { packages?: Record; @@ -148,12 +156,13 @@ describe("continuous integration workflow contract", () => { it("pins patched transitive test-toolchain dependencies", () => { const overrides = readPackageOverrides(); + const developmentDependencies = readPackageDevelopmentDependencies(); const lockedPackages = readLockedPackages(); expect(overrides).toMatchObject({ + "@hono/node-server": "2.0.10", "brace-expansion": "5.0.9", "fast-uri": "3.1.5", - hono: "4.12.34", "ip-address": "10.3.1", nanoid: "3.3.17", "@vitest/coverage-v8": { @@ -172,11 +181,16 @@ describe("continuous integration workflow contract", () => { for (const name of ["glob", "postcss"]) { expect(overrides).not.toHaveProperty(name); } + expect(developmentDependencies).toMatchObject({ + "@hono/node-server": "2.0.10", + hono: "4.12.34" + }); expect(lockedPackages["node_modules/minimatch/node_modules/brace-expansion"]).toMatchObject({ version: "5.0.9", dev: true }); - expect(lockedPackages["node_modules/fast-uri"]).toMatchObject({ version: "3.1.5" }); + const fastUri = lockedPackages["node_modules/fast-uri"]; + if (fastUri !== undefined) expect(fastUri).toMatchObject({ version: "3.1.5" }); expect(lockedPackages["node_modules/glob"]).toMatchObject({ version: "13.0.6", dev: true }); expect(lockedPackages["node_modules/hono"]).toMatchObject({ version: "4.12.34" }); expect(lockedPackages["node_modules/ip-address"]).toMatchObject({ version: "10.3.1" }); diff --git a/tests/remote-oauth-client-provider.test.ts b/tests/remote-oauth-client-provider.test.ts index 09a8ed3c..82531065 100644 --- a/tests/remote-oauth-client-provider.test.ts +++ b/tests/remote-oauth-client-provider.test.ts @@ -1,4 +1,4 @@ -import type { OAuthDiscoveryState } from "@modelcontextprotocol/sdk/client/auth.js"; +import type { OAuthDiscoveryState } from "@modelcontextprotocol/client"; import { describe, expect, it } from "vitest"; import { OAuthConnectionLifecycle } from "../src/oauth/connection-lifecycle.js"; import { OAuthConnectionRegistry, type OAuthConnectionMetadataStore } from "../src/oauth/connection-registry.js"; @@ -42,8 +42,11 @@ class MemoryCredentialStore implements OAuthCredentialStore { class DeferredHandoff implements OAuthAuthorizationHandoff { readonly redirectUrl = new URL("http://127.0.0.1:43179/oauth/callback"); - authorize(): Promise { - return Promise.resolve("fixture-code"); + authorize(): Promise<{ authorizationCode: string; issuer: string }> { + return Promise.resolve({ + authorizationCode: "fixture-code", + issuer: "https://issuer.example.test" + }); } async close(): Promise {} @@ -52,9 +55,9 @@ class DeferredHandoff implements OAuthAuthorizationHandoff { class CountingHandoff extends DeferredHandoff { authorizations = 0; - override authorize(): Promise { + override authorize(): Promise<{ authorizationCode: string; issuer: string }> { this.authorizations += 1; - return Promise.resolve("fixture-code"); + return super.authorize(); } } @@ -235,7 +238,8 @@ describe("remote OAuth client provider", () => { }); first.saveClientInformation({ client_id: "fixture-dynamic-client", - client_secret: "fixture-dynamic-client-secret" + client_secret: "fixture-dynamic-client-secret", + issuer: "https://issuer.example.test" }); await first.saveTokens({ access_token: "fixture-access-token", @@ -298,7 +302,10 @@ describe("remote OAuth client provider", () => { await expect( metadataClient.saveDiscoveryState(discovery({ authorizationServerMetadata: metadata })) ).resolves.toBeUndefined(); - await expect(metadataClient.clientInformation()).resolves.toEqual({ client_id: metadataUrl }); + await expect(metadataClient.clientInformation()).resolves.toEqual({ + client_id: metadataUrl, + issuer: "https://issuer.example.test" + }); const dynamic = providerForRegistration("dynamic"); await expect(dynamic.saveDiscoveryState(discovery())).rejects.toMatchObject({ diff --git a/tests/remote-oauth-compatibility.test.ts b/tests/remote-oauth-compatibility.test.ts index be63a571..2d0633ce 100644 --- a/tests/remote-oauth-compatibility.test.ts +++ b/tests/remote-oauth-compatibility.test.ts @@ -1,14 +1,11 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { - UnauthorizedError, - type OAuthClientProvider -} from "@modelcontextprotocol/sdk/client/auth.js"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { Client, UnauthorizedError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import type { + OAuthClientProvider, OAuthClientInformationMixed, OAuthClientMetadata, + OAuthDiscoveryState, OAuthTokens -} from "@modelcontextprotocol/sdk/shared/auth.js"; +} from "@modelcontextprotocol/client"; import { afterEach, describe, expect, it } from "vitest"; import { startOAuthCompatibilityProbe, @@ -21,6 +18,7 @@ class DeterministicOAuthClientProvider implements OAuthClientProvider { private savedTokens?: OAuthTokens; private verifier?: string; private redirect?: URL; + private discovery?: OAuthDiscoveryState; get clientMetadata(): OAuthClientMetadata { return { @@ -65,6 +63,14 @@ class DeterministicOAuthClientProvider implements OAuthClientProvider { return this.verifier; } + saveDiscoveryState(state: OAuthDiscoveryState): void { + this.discovery = structuredClone(state); + } + + discoveryState(): OAuthDiscoveryState | undefined { + return this.discovery === undefined ? undefined : structuredClone(this.discovery); + } + authorizationRedirect(): URL | undefined { return this.redirect ? new URL(this.redirect) : undefined; } @@ -119,7 +125,7 @@ describe("standards-compatible remote OAuth probe", () => { expect(callback.searchParams.get("code")).toBe("fixture-authorization-code"); expect(callback.searchParams.get("state")).toBe("miftah-compatibility-state"); - await firstTransport.finishAuth("fixture-authorization-code"); + await firstTransport.finishAuth(callback.searchParams); expect(upstream.tokenExchanges()).toEqual([ { clientId: "miftah-compatibility-client", diff --git a/tests/remote-oauth-runtime.test.ts b/tests/remote-oauth-runtime.test.ts index 318be5ee..841e1dc6 100644 --- a/tests/remote-oauth-runtime.test.ts +++ b/tests/remote-oauth-runtime.test.ts @@ -1,5 +1,4 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { createHash } from "node:crypto"; import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -67,7 +66,7 @@ class SimulatedBrowserHandoff implements OAuthAuthorizationHandoff { async authorize( authorizationUrl: URL, expected: { readonly state: string; readonly issuer: string } - ): Promise { + ): Promise<{ authorizationCode: string; issuer: string }> { this.onAuthorize(); const response = await this.upstream.fetch(authorizationUrl, { redirect: "manual" }); const callback = new URL(response.headers.get("location") ?? "invalid:"); @@ -75,7 +74,7 @@ class SimulatedBrowserHandoff implements OAuthAuthorizationHandoff { expect(callback.searchParams.get("iss")).toBe(expected.issuer); const code = callback.searchParams.get("code"); if (code === null) throw new Error("fixture callback did not contain a code"); - return code; + return { authorizationCode: code, issuer: expected.issuer }; } async close(): Promise {} diff --git a/tests/remote-oauth-transport.test.ts b/tests/remote-oauth-transport.test.ts index d2d96057..f2d2ca01 100644 --- a/tests/remote-oauth-transport.test.ts +++ b/tests/remote-oauth-transport.test.ts @@ -49,7 +49,7 @@ class SimulatedBrowserHandoff implements OAuthAuthorizationHandoff { async authorize( authorizationUrl: URL, expected: { readonly state: string; readonly issuer: string } - ): Promise { + ): Promise<{ authorizationCode: string; issuer: string }> { const response = await this.upstream.fetch(authorizationUrl, { redirect: "manual" }); const location = response.headers.get("location"); if (location === null) throw new Error("fixture authorization did not redirect"); @@ -58,7 +58,7 @@ class SimulatedBrowserHandoff implements OAuthAuthorizationHandoff { expect(callback.searchParams.get("iss")).toBe(expected.issuer); const code = callback.searchParams.get("code"); if (code === null) throw new Error("fixture callback did not contain a code"); - return code; + return { authorizationCode: code, issuer: expected.issuer }; } async close(): Promise { @@ -187,7 +187,10 @@ describe("profile-bound remote OAuth transport", () => { lifecycle, handoff: { redirectUrl: new URL("http://127.0.0.1:43179/oauth/callback"), - authorize: async () => "fixture-code", + authorize: async () => ({ + authorizationCode: "fixture-code", + issuer: "https://mcp.example.test" + }), close: async () => { closeCount += 1; } diff --git a/tests/remote-transport.test.ts b/tests/remote-transport.test.ts index 5798bc2e..a69ea763 100644 --- a/tests/remote-transport.test.ts +++ b/tests/remote-transport.test.ts @@ -1,14 +1,26 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { + Client, + InMemoryTransport, + SdkErrorCode, + SdkHttpError, + SseError, +} from "@modelcontextprotocol/client"; import { setTimeout as delay } from "node:timers/promises"; import { afterEach, describe, expect, it } from "vitest"; import { validateConfig } from "../src/config/validate-config.js"; import { MiftahServer } from "../src/mcp/server/miftah-server.js"; import { ProfileManager } from "../src/profiles/profile-manager.js"; +import { asRemoteError } from "../src/upstream/remote-error.js"; import { UpstreamProcessManager } from "../src/upstream/upstream-process-manager.js"; -import { startFakeRemoteUpstream, type FakeRemoteUpstream } from "./helpers/fake-remote-upstream.js"; - -async function waitFor(condition: () => boolean, timeoutMs = 500): Promise { +import { + startFakeRemoteUpstream, + type FakeRemoteUpstream, +} from "./helpers/fake-remote-upstream.js"; + +async function waitFor( + condition: () => boolean, + timeoutMs = 500, +): Promise { const deadline = Date.now() + timeoutMs; while (!condition()) { if (Date.now() >= deadline) return false; @@ -34,49 +46,89 @@ describe("remote upstream transports", () => { upstream: { transport: "streamable-http", url: upstream.streamableHttpUrl, - headers: { Authorization: "Bearer base-secret", "X-Profile": "base" } + headers: { Authorization: "Bearer base-secret", "X-Profile": "base" }, }, profiles: { - work: { headers: { authorization: "Bearer work-secret", "x-profile": "work" } }, - personal: { headers: { AUTHORIZATION: "Bearer personal-secret", "X-PROFILE": "personal" } } + work: { + headers: { authorization: "Bearer work-secret", "x-profile": "work" }, + }, + personal: { + headers: { + AUTHORIZATION: "Bearer personal-secret", + "X-PROFILE": "personal", + }, + }, }, - security: { allowProfileSwitchingFromMcp: true } + security: { allowProfileSwitchingFromMcp: true }, + }); + const manager = new UpstreamProcessManager( + config.upstream!, + config.profiles, + ); + const wrapper = new MiftahServer( + config, + new ProfileManager(config), + manager, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const client = new Client({ + name: "remote-transport-test", + version: "1.0.0", }); - const manager = new UpstreamProcessManager(config.upstream!, config.profiles); - const wrapper = new MiftahServer(config, new ProfileManager(config), manager); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "remote-transport-test", version: "1.0.0" }); try { - await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + await Promise.all([ + wrapper.connect(serverTransport), + client.connect(clientTransport), + ]); - expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); - expect(await client.callTool({ name: "whoami", arguments: {} })).toMatchObject({ - content: [{ type: "text", text: "work" }] + expect( + (await client.listTools()).tools.map((tool) => tool.name), + ).toContain("whoami"); + expect( + await client.callTool({ name: "whoami", arguments: {} }), + ).toMatchObject({ + content: [{ type: "text", text: "work" }], }); - expect(await client.readResource({ uri: "account://current" })).toMatchObject({ - contents: [{ text: "work" }] + expect( + await client.readResource({ uri: "account://current" }), + ).toMatchObject({ + contents: [{ text: "work" }], }); expect(await client.getPrompt({ name: "account_prompt" })).toMatchObject({ - messages: [{ content: { text: "work" } }] + messages: [{ content: { text: "work" } }], }); - await client.callTool({ name: "miftah_use_profile", arguments: { profile: "personal" } }); - expect(await client.callTool({ name: "whoami", arguments: {} })).toMatchObject({ - content: [{ type: "text", text: "personal" }] + await client.callTool({ + name: "miftah_use_profile", + arguments: { profile: "personal" }, + }); + expect( + await client.callTool({ name: "whoami", arguments: {} }), + ).toMatchObject({ + content: [{ type: "text", text: "personal" }], }); - const workHeaders = upstream.requests().filter((request) => request.headers["x-profile"] === "work"); - const personalHeaders = upstream.requests().filter((request) => request.headers["x-profile"] === "personal"); + const workHeaders = upstream + .requests() + .filter((request) => request.headers["x-profile"] === "work"); + const personalHeaders = upstream + .requests() + .filter((request) => request.headers["x-profile"] === "personal"); expect(workHeaders).not.toHaveLength(0); expect(personalHeaders).not.toHaveLength(0); - expect(workHeaders.map((request) => request.headers.authorization)).toEqual( - expect.arrayContaining(["Bearer work-secret"]) - ); - expect(personalHeaders.map((request) => request.headers.authorization)).toEqual( - expect.arrayContaining(["Bearer personal-secret"]) - ); - expect(JSON.stringify(await client.callTool({ name: "miftah_health", arguments: {} }))).not.toContain("secret"); + expect( + workHeaders.map((request) => request.headers.authorization), + ).toEqual(expect.arrayContaining(["Bearer work-secret"])); + expect( + personalHeaders.map((request) => request.headers.authorization), + ).toEqual(expect.arrayContaining(["Bearer personal-secret"])); + expect( + JSON.stringify( + await client.callTool({ name: "miftah_health", arguments: {} }), + ), + ).not.toContain("secret"); } finally { await client.close(); await wrapper.close(); @@ -90,19 +142,39 @@ describe("remote upstream transports", () => { version: "1", name: "remote-cancellation", defaultProfile: "work", - upstream: { transport: "streamable-http", url: upstream.streamableHttpUrl }, - profiles: { work: { headers: { "X-Profile": "work" } } } + upstream: { + transport: "streamable-http", + url: upstream.streamableHttpUrl, + }, + profiles: { work: { headers: { "X-Profile": "work" } } }, + }); + const manager = new UpstreamProcessManager( + config.upstream!, + config.profiles, + ); + const wrapper = new MiftahServer( + config, + new ProfileManager(config), + manager, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const client = new Client({ + name: "remote-cancellation-test", + version: "1.0.0", }); - const manager = new UpstreamProcessManager(config.upstream!, config.profiles); - const wrapper = new MiftahServer(config, new ProfileManager(config), manager); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "remote-cancellation-test", version: "1.0.0" }); const controller = new AbortController(); try { - await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); - - const pending = client.callTool({ name: "whoami", arguments: {} }, undefined, { signal: controller.signal }); + await Promise.all([ + wrapper.connect(serverTransport), + client.connect(clientTransport), + ]); + + const pending = client.callTool( + { name: "whoami", arguments: {} }, + { signal: controller.signal }, + ); await expect.poll(() => upstream.toolCallRequests()).toBe(1); controller.abort("test cancellation"); @@ -115,30 +187,48 @@ describe("remote upstream transports", () => { }); it("forwards progress from a streamable HTTP upstream", async () => { - const upstream = await startFakeRemoteUpstream({ emitCallToolProgress: true }); + const upstream = await startFakeRemoteUpstream({ + emitCallToolProgress: true, + }); upstreams.push(upstream); const config = validateConfig({ version: "1", name: "remote-progress", defaultProfile: "work", - upstream: { transport: "streamable-http", url: upstream.streamableHttpUrl }, - profiles: { work: { headers: { "X-Profile": "work" } } } + upstream: { + transport: "streamable-http", + url: upstream.streamableHttpUrl, + }, + profiles: { work: { headers: { "X-Profile": "work" } } }, + }); + const manager = new UpstreamProcessManager( + config.upstream!, + config.profiles, + ); + const wrapper = new MiftahServer( + config, + new ProfileManager(config), + manager, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const client = new Client({ + name: "remote-progress-test", + version: "1.0.0", }); - const manager = new UpstreamProcessManager(config.upstream!, config.profiles); - const wrapper = new MiftahServer(config, new ProfileManager(config), manager); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "remote-progress-test", version: "1.0.0" }); const progressUpdates: unknown[] = []; try { - await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + await Promise.all([ + wrapper.connect(serverTransport), + client.connect(clientTransport), + ]); expect( await client.callTool( { name: "whoami", arguments: {} }, - undefined, - { onprogress: (progress) => progressUpdates.push(progress) } - ) + { onprogress: (progress) => progressUpdates.push(progress) }, + ), ).toMatchObject({ content: [{ type: "text", text: "work" }] }); expect(progressUpdates).toEqual([{ progress: 1, total: 2 }]); } finally { @@ -152,7 +242,7 @@ describe("remote upstream transports", () => { upstreams.push(upstream); const manager = new UpstreamProcessManager( { transport: "streamable-http", url: upstream.streamableHttpUrl }, - { work: {} } + { work: {} }, ); try { @@ -181,7 +271,7 @@ describe("remote upstream transports", () => { const manager = new UpstreamProcessManager( { transport: "streamable-http", url: upstream.streamableHttpUrl }, { work: {} }, - { shutdownTimeoutMs: 50 } + { shutdownTimeoutMs: 50 }, ); try { @@ -191,7 +281,9 @@ describe("remote upstream transports", () => { const closeStartedAt = Date.now(); await manager.close(); expect(Date.now() - closeStartedAt).toBeLessThan(500); - expect(await waitFor(() => upstream.hangingStreamableDeleteClosed())).toBe(true); + expect( + await waitFor(() => upstream.hangingStreamableDeleteClosed()), + ).toBe(true); } finally { upstream.releaseHangingStreamableDelete(); await manager.close(); @@ -203,13 +295,15 @@ describe("remote upstream transports", () => { upstreams.push(upstream); const manager = new UpstreamProcessManager( { transport: "http", url: upstream.streamableHttpUrl }, - { work: { headers: { "X-Profile": "work" } } } + { work: { headers: { "X-Profile": "work" } } }, ); try { const session = await manager.get("work"); - expect(await session.callTool({ name: "whoami", arguments: {} })).toMatchObject({ - content: [{ type: "text", text: "work" }] + expect( + await session.callTool({ name: "whoami", arguments: {} }), + ).toMatchObject({ + content: [{ type: "text", text: "work" }], }); } finally { await manager.close(); @@ -219,59 +313,101 @@ describe("remote upstream transports", () => { it("reports remote HTTP startup status without exposing an upstream response body", async () => { const upstream = await startFakeRemoteUpstream({ initializationStatus: 401, - initializationBody: "Bearer server-secret was rejected" + initializationBody: "Bearer server-secret was rejected", }); upstreams.push(upstream); const manager = new UpstreamProcessManager( { transport: "streamable-http", url: upstream.streamableHttpUrl, - headers: { Authorization: "Bearer configured-secret" } + headers: { Authorization: "Bearer configured-secret" }, }, - { work: {} } + { work: {} }, ); try { - const error = await manager.get("work").catch((caught: unknown) => caught); + const error = await manager + .get("work") + .catch((caught: unknown) => caught); expect(error).toMatchObject({ code: "UPSTREAM_HTTP_ERROR", - message: "UPSTREAM_HTTP_ERROR: streamable-http upstream for profile 'work' returned HTTP 401", - details: { profile: "work", transport: "streamable-http", status: 401 } + message: + "UPSTREAM_HTTP_ERROR: streamable-http upstream for profile 'work' returned HTTP 401", + details: { profile: "work", transport: "streamable-http", status: 401 }, }); - expect(`${error instanceof Error ? error.message : ""} ${JSON.stringify(error)}`).not.toContain("secret"); + expect( + `${error instanceof Error ? error.message : ""} ${JSON.stringify(error)}`, + ).not.toContain("secret"); } finally { await manager.close(); } }); + it("ignores SDK v2 remote errors that do not carry a valid HTTP status", () => { + expect( + asRemoteError( + "work", + "streamable-http", + new SdkHttpError(SdkErrorCode.NotConnected, "failed", { status: 42 }), + ), + ).toBeUndefined(); + expect( + asRemoteError( + "work", + "sse", + new SseError(undefined, "failed", {} as ErrorEvent), + ), + ).toBeUndefined(); + }); + it("reports remote MCP protocol errors without exposing an upstream error message", async () => { const upstream = await startFakeRemoteUpstream({ - callToolError: { code: -32603, message: "remote-server-secret must not escape" } + callToolError: { + code: -32603, + message: "remote-server-secret must not escape", + }, }); upstreams.push(upstream); const config = validateConfig({ version: "1", name: "remote-errors", defaultProfile: "work", - upstream: { transport: "streamable-http", url: upstream.streamableHttpUrl }, - profiles: { work: {} } + upstream: { + transport: "streamable-http", + url: upstream.streamableHttpUrl, + }, + profiles: { work: {} }, + }); + const manager = new UpstreamProcessManager( + config.upstream!, + config.profiles, + ); + const wrapper = new MiftahServer( + config, + new ProfileManager(config), + manager, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const client = new Client({ + name: "remote-protocol-test", + version: "1.0.0", }); - const manager = new UpstreamProcessManager(config.upstream!, config.profiles); - const wrapper = new MiftahServer(config, new ProfileManager(config), manager); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "remote-protocol-test", version: "1.0.0" }); try { - await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + await Promise.all([ + wrapper.connect(serverTransport), + client.connect(clientTransport), + ]); const result = await client.callTool({ name: "whoami", arguments: {} }); expect(result).toMatchObject({ isError: true, content: [ { type: "text", - text: "UPSTREAM_PROTOCOL_ERROR: streamable-http upstream for profile 'work' returned MCP error -32603" - } - ] + text: "UPSTREAM_PROTOCOL_ERROR: streamable-http upstream for profile 'work' returned MCP error -32603", + }, + ], }); expect(JSON.stringify(result)).not.toContain("remote-server-secret"); } finally { @@ -287,16 +423,33 @@ describe("remote upstream transports", () => { version: "1", name: "remote-operation-errors", defaultProfile: "work", - upstream: { transport: "streamable-http", url: upstream.streamableHttpUrl }, - profiles: { work: {} } + upstream: { + transport: "streamable-http", + url: upstream.streamableHttpUrl, + }, + profiles: { work: {} }, + }); + const manager = new UpstreamProcessManager( + config.upstream!, + config.profiles, + ); + const wrapper = new MiftahServer( + config, + new ProfileManager(config), + manager, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const client = new Client({ + name: "remote-operation-error-test", + version: "1.0.0", }); - const manager = new UpstreamProcessManager(config.upstream!, config.profiles); - const wrapper = new MiftahServer(config, new ProfileManager(config), manager); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "remote-operation-error-test", version: "1.0.0" }); try { - await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + await Promise.all([ + wrapper.connect(serverTransport), + client.connect(clientTransport), + ]); await client.listTools(); upstream.failNextStreamableRequest(503, "server-secret must not escape"); @@ -306,9 +459,9 @@ describe("remote upstream transports", () => { content: [ { type: "text", - text: "UPSTREAM_HTTP_ERROR: streamable-http upstream for profile 'work' returned HTTP 503" - } - ] + text: "UPSTREAM_HTTP_ERROR: streamable-http upstream for profile 'work' returned HTTP 503", + }, + ], }); expect(JSON.stringify(result)).not.toContain("server-secret"); } finally { @@ -327,29 +480,48 @@ describe("remote upstream transports", () => { upstream: { transport: "sse", url: upstream.sseUrl, - headers: { Authorization: "Bearer base-secret", "X-Profile": "base" } + headers: { Authorization: "Bearer base-secret", "X-Profile": "base" }, }, profiles: { - work: { headers: { authorization: "Bearer work-secret", "x-profile": "work" } } - } + work: { + headers: { authorization: "Bearer work-secret", "x-profile": "work" }, + }, + }, }); - const manager = new UpstreamProcessManager(config.upstream!, config.profiles); - const wrapper = new MiftahServer(config, new ProfileManager(config), manager); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const manager = new UpstreamProcessManager( + config.upstream!, + config.profiles, + ); + const wrapper = new MiftahServer( + config, + new ProfileManager(config), + manager, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); const client = new Client({ name: "legacy-sse-test", version: "1.0.0" }); try { - await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + await Promise.all([ + wrapper.connect(serverTransport), + client.connect(clientTransport), + ]); - expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); - expect(await client.callTool({ name: "whoami", arguments: {} })).toMatchObject({ - content: [{ type: "text", text: "work" }] + expect( + (await client.listTools()).tools.map((tool) => tool.name), + ).toContain("whoami"); + expect( + await client.callTool({ name: "whoami", arguments: {} }), + ).toMatchObject({ + content: [{ type: "text", text: "work" }], }); - expect(await client.readResource({ uri: "account://current" })).toMatchObject({ - contents: [{ text: "work" }] + expect( + await client.readResource({ uri: "account://current" }), + ).toMatchObject({ + contents: [{ text: "work" }], }); expect(await client.getPrompt({ name: "account_prompt" })).toMatchObject({ - messages: [{ content: { text: "work" } }] + messages: [{ content: { text: "work" } }], }); expect(upstream.requests()).toEqual( @@ -359,10 +531,10 @@ describe("remote upstream transports", () => { path: "/sse", headers: expect.objectContaining({ authorization: "Bearer work-secret", - "x-profile": "work" - }) - }) - ]) + "x-profile": "work", + }), + }), + ]), ); } finally { await client.close(); @@ -378,15 +550,29 @@ describe("remote upstream transports", () => { name: "legacy-sse-errors", defaultProfile: "work", upstream: { transport: "sse", url: upstream.sseUrl }, - profiles: { work: {} } + profiles: { work: {} }, + }); + const manager = new UpstreamProcessManager( + config.upstream!, + config.profiles, + ); + const wrapper = new MiftahServer( + config, + new ProfileManager(config), + manager, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const client = new Client({ + name: "legacy-sse-error-test", + version: "1.0.0", }); - const manager = new UpstreamProcessManager(config.upstream!, config.profiles); - const wrapper = new MiftahServer(config, new ProfileManager(config), manager); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "legacy-sse-error-test", version: "1.0.0" }); try { - await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + await Promise.all([ + wrapper.connect(serverTransport), + client.connect(clientTransport), + ]); await client.listTools(); upstream.failNextSsePost(502, "legacy-sse-server-secret must not escape"); @@ -396,9 +582,9 @@ describe("remote upstream transports", () => { content: [ { type: "text", - text: "UPSTREAM_HTTP_ERROR: sse upstream for profile 'work' returned HTTP 502" - } - ] + text: "UPSTREAM_HTTP_ERROR: sse upstream for profile 'work' returned HTTP 502", + }, + ], }); expect(JSON.stringify(result)).not.toContain("legacy-sse-server-secret"); } finally { diff --git a/tests/stateless-profile-context-runtime.test.ts b/tests/stateless-profile-context-runtime.test.ts index e34b9ae8..32859102 100644 --- a/tests/stateless-profile-context-runtime.test.ts +++ b/tests/stateless-profile-context-runtime.test.ts @@ -1,8 +1,7 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; -import type { Transport, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { CallToolResultSchema, type JSONRPCMessage, type Tool } from "@modelcontextprotocol/sdk/types.js"; +import { CallToolResultSchema } from "@modelcontextprotocol/core"; +import { InMemoryTransport } from "@modelcontextprotocol/server"; +import type { AuthInfo, Transport, TransportSendOptions, JSONRPCMessage, Tool } from "@modelcontextprotocol/server"; +import { Client } from "@modelcontextprotocol/client"; import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; diff --git a/tests/tool-registry.test.ts b/tests/tool-registry.test.ts index 63b986e1..670a841a 100644 --- a/tests/tool-registry.test.ts +++ b/tests/tool-registry.test.ts @@ -1,4 +1,4 @@ -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import type { Tool } from "@modelcontextprotocol/server"; import { describe, expect, it } from "vitest"; import { ToolRegistry } from "../src/mcp/server/tool-registry.js"; diff --git a/tsup.config.ts b/tsup.config.ts index ebf67c6b..f4066426 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -1,6 +1,26 @@ +import { copyFile, mkdir } from "node:fs/promises"; import { defineConfig } from "tsup"; import { packageVersion } from "./build/package-version.js"; +async function copyBundledDependencyLicenses(): Promise { + const destination = new URL("./dist/third-party/", import.meta.url); + await mkdir(destination, { recursive: true }); + await Promise.all([ + copyFile( + new URL("./node_modules/@modelcontextprotocol/node/LICENSE", import.meta.url), + new URL("./modelcontextprotocol-node.LICENSE", destination) + ), + copyFile( + new URL("./node_modules/@hono/node-server/LICENSE", import.meta.url), + new URL("./hono-node-server.LICENSE", destination) + ), + copyFile( + new URL("./node_modules/hono/LICENSE", import.meta.url), + new URL("./hono.LICENSE", destination) + ) + ]); +} + export default defineConfig({ entry: { "cli/main": "src/cli/main.ts", @@ -11,6 +31,11 @@ export default defineConfig({ format: ["esm"], dts: true, clean: true, + // The v2 Node adapter still constrains @hono/node-server to vulnerable 1.x. + // Bundle the tested patched adapter into the CLI instead of exporting that + // unsatisfied transitive range to Miftah's installed production tree. + noExternal: ["@modelcontextprotocol/node", "@hono/node-server", "hono"], + onSuccess: copyBundledDependencyLicenses, publicDir: "assets", sourcemap: true, define: { From dee2c874c06d1fa2087510caf3a51f0149744c68 Mon Sep 17 00:00:00 2001 From: mohammed naji Date: Tue, 11 Aug 2026 17:42:57 +0400 Subject: [PATCH 2/4] fix: generate portable MCP peer lockfile --- CHANGELOG.md | 2 +- package-lock.json | 819 +++++++++++++++++++++++- package.json | 2 +- tests/mcp-v2-migration-contract.test.ts | 2 +- tests/package-contract.test.ts | 4 +- 5 files changed, 823 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04e708d0..040ec782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ All notable changes to this project will be documented in this file. The format ### Changed -- [#363](https://github.com/mohanagy/miftah/issues/363) Replaced the monolithic MCP TypeScript SDK v1 dependency with the stable v2 `client`, `core`, `node`, `server`, and legacy-server packages and migrated runtime schemas to Zod 4. Direct consumers of the old monolithic SDK deep imports must move to the corresponding split package. The CLI bundles the v2 Node adapter with patched `@hono/node-server` and Hono builds so a fresh Miftah install does not inherit the Node package's still-vulnerable 1.x adapter range; custom embedding hosts own their direct Node adapter version. Native OAuth callback completion now carries the authorization-server issuer required by the v2 provider contract; Miftah continues to validate and round-trip that issuer without exposing tokens or client secrets. +- [#363](https://github.com/mohanagy/miftah/issues/363) Replaced the monolithic MCP TypeScript SDK v1 dependency with the stable v2 split packages and migrated runtime schemas to Zod 4. Runtime consumers receive only `client`, `core`, and `server`; the Node adapter and frozen legacy server remain build/test dependencies. Direct consumers of the old monolithic SDK deep imports must move to the corresponding split package. The CLI bundles the v2 Node adapter with patched `@hono/node-server` and Hono builds so a fresh Miftah install does not inherit the Node package's still-vulnerable 1.x adapter range; custom embedding hosts own their direct Node adapter version. Native OAuth callback completion now carries the authorization-server issuer required by the v2 provider contract; Miftah continues to validate and round-trip that issuer without exposing tokens or client secrets. ## [1.0.0] - 2026-08-11 diff --git a/package-lock.json b/package-lock.json index 52f4c95e..e8a2dbc0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,6 @@ "@modelcontextprotocol/client": "^2.0.0", "@modelcontextprotocol/core": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", - "@modelcontextprotocol/server-legacy": "^2.0.0", "@napi-rs/keyring": "1.3.0", "dotenv": "^17.4.2", "zod": "^4.2.0", @@ -25,6 +24,7 @@ "@eslint/js": "^10.0.1", "@hono/node-server": "2.0.10", "@modelcontextprotocol/node": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0", "@types/node": "^22.15.30", "@vitest/coverage-v8": "^3.2.7", "esbuild": "0.28.1", @@ -881,6 +881,7 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server-legacy/-/server-legacy-2.0.0.tgz", "integrity": "sha512-LnffC1BSqFMHtMQxEz92lqDpHWma+ErV3ghdHDgdkCyYzVcCYKcUT5loq4kflty+Bf9C9qjJqbnphyBWyCqo8Q==", "deprecated": "This package is a frozen copy of v1's SSE transport and OAuth Authorization Server helpers for migration purposes only. Use StreamableHTTP from @modelcontextprotocol/server and a dedicated OAuth server in production. Will not receive new features.", + "dev": true, "license": "MIT", "dependencies": { "@modelcontextprotocol/core": "2.0.0", @@ -1954,6 +1955,21 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/acorn": { "version": "8.17.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz", @@ -2016,6 +2032,47 @@ "node": "18 || 20 || >=22" } }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/bundle-require": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", @@ -2036,6 +2093,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -2051,6 +2109,39 @@ "node": ">=8" } }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/chai": { "version": "5.3.3", "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", @@ -2121,19 +2212,58 @@ "node": "^14.18.0 || >=16.10.0" } }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/content-type": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 0.6" } }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6.6.0" + } + }, "node_modules/cors": { "version": "2.8.6", "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dev": true, "license": "MIT", "dependencies": { "object-assign": "^4", @@ -2200,6 +2330,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -2217,6 +2348,63 @@ "url": "https://dotenvx.com" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -2224,6 +2412,20 @@ "dev": true, "license": "MIT" }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", @@ -2266,6 +2468,14 @@ "@esbuild/win32-x64": "0.28.1" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -2468,6 +2678,17 @@ "node": ">=0.10.0" } }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/eventsource": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", @@ -2499,10 +2720,56 @@ "node": ">=12.0.0" } }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/express-rate-limit": { "version": "8.5.2", "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz", "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==", + "dev": true, "license": "MIT", "dependencies": { "ip-address": "^10.2.0" @@ -2569,6 +2836,29 @@ "node": ">=16.0.0" } }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -2619,6 +2909,28 @@ "dev": true, "license": "ISC" }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2634,6 +2946,58 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/glob": { "version": "13.0.6", "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", @@ -2665,6 +3029,20 @@ "node": ">=10.13.0" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -2675,6 +3053,34 @@ "node": ">=8" } }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hono": { "version": "4.12.34", "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.34.tgz", @@ -2696,6 +3102,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, "license": "MIT", "dependencies": { "depd": "~2.0.0", @@ -2716,6 +3123,7 @@ "version": "0.7.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -2752,17 +3160,30 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, "license": "ISC" }, "node_modules/ip-address": { "version": "10.3.1", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.3.1.tgz", "integrity": "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g==", + "dev": true, "license": "MIT", "engines": { "node": ">= 12" } }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2786,6 +3207,14 @@ "node": ">=0.10.0" } }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -3011,6 +3440,75 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/minimatch": { "version": "10.2.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", @@ -3108,15 +3606,66 @@ "dev": true, "license": "MIT" }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" } }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "wrappy": "1" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -3167,6 +3716,17 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3203,6 +3763,18 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -3353,6 +3925,21 @@ "node": ">= 0.8.0" } }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -3363,10 +3950,44 @@ "node": ">=6" } }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/raw-body": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dev": true, "license": "MIT", "dependencies": { "bytes": "~3.1.2", @@ -3447,10 +4068,29 @@ "fsevents": "~2.3.2" } }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, "license": "MIT" }, "node_modules/semver": { @@ -3466,10 +4106,60 @@ "node": ">=10" } }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, "license": "ISC" }, "node_modules/shebang-command": { @@ -3493,6 +4183,86 @@ "node": ">=8" } }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -3531,6 +4301,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -3702,6 +4473,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.6" @@ -3803,6 +4575,41 @@ "node": ">= 0.8.0" } }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -3859,6 +4666,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -3878,6 +4686,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -4096,6 +4905,14 @@ "node": ">=0.10.0" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC", + "peer": true + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index c9bb5c8e..9a5ca4ee 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,6 @@ "@modelcontextprotocol/client": "^2.0.0", "@modelcontextprotocol/core": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", - "@modelcontextprotocol/server-legacy": "^2.0.0", "@napi-rs/keyring": "1.3.0", "dotenv": "^17.4.2", "zod": "^4.2.0", @@ -75,6 +74,7 @@ "@eslint/js": "^10.0.1", "@hono/node-server": "2.0.10", "@modelcontextprotocol/node": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0", "@types/node": "^22.15.30", "@vitest/coverage-v8": "^3.2.7", "esbuild": "0.28.1", diff --git a/tests/mcp-v2-migration-contract.test.ts b/tests/mcp-v2-migration-contract.test.ts index ac9df63a..afcd447c 100644 --- a/tests/mcp-v2-migration-contract.test.ts +++ b/tests/mcp-v2-migration-contract.test.ts @@ -16,12 +16,12 @@ describe("MCP TypeScript SDK v2 migration contract", () => { "@modelcontextprotocol/client": "^2.0.0", "@modelcontextprotocol/core": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", - "@modelcontextprotocol/server-legacy": "^2.0.0", zod: "^4.2.0" }); expect(manifest.devDependencies).toMatchObject({ "@hono/node-server": "2.0.10", "@modelcontextprotocol/node": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0", hono: "4.12.34" }); }); diff --git a/tests/package-contract.test.ts b/tests/package-contract.test.ts index 90b08671..13e1d67b 100644 --- a/tests/package-contract.test.ts +++ b/tests/package-contract.test.ts @@ -799,12 +799,12 @@ describe("package metadata contract", () => { expect(manifest.dependencies).toMatchObject({ "@modelcontextprotocol/client": "^2.0.0", "@modelcontextprotocol/core": "^2.0.0", - "@modelcontextprotocol/server": "^2.0.0", - "@modelcontextprotocol/server-legacy": "^2.0.0" + "@modelcontextprotocol/server": "^2.0.0" }); expect(manifest.devDependencies).toMatchObject({ "@hono/node-server": "2.0.10", "@modelcontextprotocol/node": "^2.0.0", + "@modelcontextprotocol/server-legacy": "^2.0.0", hono: "4.12.34" }); expect(manifest.overrides?.["@hono/node-server"]).toBe("2.0.10"); From 89d5564986b103d0e81fdb9f4a528e1459e8bc63 Mon Sep 17 00:00:00 2001 From: mohammed naji Date: Tue, 11 Aug 2026 18:17:07 +0400 Subject: [PATCH 3/4] fix: address MCP v2 review findings --- scripts/build-test-fixture.mjs | 106 ++++++++++++++----- src/cli/main.ts | 7 +- src/mcp/server/miftah-server.ts | 4 +- src/oauth/remote-oauth-client-provider.ts | 1 + src/runtime/create-miftah-runtime.ts | 7 +- tests/fixtures/fake-upstream-bundled.mjs | 6 +- tests/mcp-v2-migration-contract.test.ts | 1 + tests/mcp-v2-serving.test.ts | 44 +++++++- tests/remote-oauth-client-provider.test.ts | 3 +- tests/test-harness-resource-contract.test.ts | 27 ++++- 10 files changed, 166 insertions(+), 40 deletions(-) diff --git a/scripts/build-test-fixture.mjs b/scripts/build-test-fixture.mjs index b02fab5e..34d4117f 100644 --- a/scripts/build-test-fixture.mjs +++ b/scripts/build-test-fixture.mjs @@ -1,40 +1,92 @@ import { error as logError } from "node:console"; import { readFile, writeFile } from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { dirname, join, resolve } from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; import { build } from "esbuild"; +import ts from "typescript"; const root = dirname(dirname(fileURLToPath(import.meta.url))); const outputPath = join(root, "tests", "fixtures", "fake-upstream-bundled.mjs"); -const result = await build({ - absWorkingDir: root, - entryPoints: ["tests/fixtures/fake-upstream-runtime.mjs"], - bundle: true, - platform: "node", - format: "esm", - target: "node20", - minify: true, - legalComments: "none", - write: false -}); -// esbuild preserves whitespace-only lines inside dependency template literals. -// They are behaviorally inert but fail `git diff --check` in the committed fixture. -const bundledSource = result.outputFiles[0].text.replace(/^[\t ]+$/gm, ""); - -if (process.argv.includes("--check")) { - let currentSource; - try { - currentSource = await readFile(outputPath, "utf8"); - } catch { - currentSource = undefined; + +function escapedWhitespace(value) { + return [...value].map((character) => character === "\t" ? "\\t" : "\\x20").join(""); +} + +/** Preserves cooked template values while removing source lines that contain only whitespace. */ +export function normalizeTemplateLiteralWhitespace(source) { + const sourceFile = ts.createSourceFile("fake-upstream-bundled.mjs", source, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS); + if (sourceFile.parseDiagnostics.length > 0) { + throw new Error("The bundled fake upstream fixture could not be parsed before normalization."); } + const replacements = []; + const visit = (node) => { + if ( + ts.isNoSubstitutionTemplateLiteral(node) || + ts.isTemplateHead(node) || + ts.isTemplateMiddle(node) || + ts.isTemplateTail(node) + ) { + const value = source.slice(node.getStart(sourceFile), node.getEnd()); + if (/^[\t ]+$/mu.test(value)) { + const template = ts.isNoSubstitutionTemplateLiteral(node) + ? node + : ts.isTemplateExpression(node.parent) + ? node.parent + : node.parent.parent; + if (ts.isTaggedTemplateExpression(template.parent)) { + throw new Error("Cannot safely normalize whitespace inside a tagged template literal."); + } + replacements.push({ + start: node.getStart(sourceFile), + end: node.getEnd(), + value: value.replace(/^[\t ]+$/gmu, escapedWhitespace) + }); + } + } + ts.forEachChild(node, visit); + }; + visit(sourceFile); + return replacements + .sort((left, right) => right.start - left.start) + .reduce((result, replacement) => + `${result.slice(0, replacement.start)}${replacement.value}${result.slice(replacement.end)}`, source); +} - if (currentSource !== bundledSource) { - logError("The bundled fake upstream fixture is stale. Run `npm run build:test-fixture`."); - process.exitCode = 1; +/** Bundles the process fixture without leaving whitespace-only lines in template literals. */ +export async function buildTestFixtureSource(entryPoint = "tests/fixtures/fake-upstream-runtime.mjs") { + const result = await build({ + absWorkingDir: root, + entryPoints: [entryPoint], + bundle: true, + platform: "node", + format: "esm", + target: "node20", + minify: true, + legalComments: "none", + write: false + }); + return normalizeTemplateLiteralWhitespace(result.outputFiles[0].text); +} + +async function main() { + const bundledSource = await buildTestFixtureSource(); + if (process.argv.includes("--check")) { + let currentSource; + try { + currentSource = await readFile(outputPath, "utf8"); + } catch { + currentSource = undefined; + } + + if (currentSource !== bundledSource) { + logError("The bundled fake upstream fixture is stale. Run `npm run build:test-fixture`."); + process.exitCode = 1; + } + } else { + await writeFile(outputPath, bundledSource); } -} else { - await writeFile(outputPath, bundledSource); } + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main(); diff --git a/src/cli/main.ts b/src/cli/main.ts index 522f958b..4949c8e8 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -72,7 +72,12 @@ async function serve(configPath: string, transportKind = "stdio"): Promise process.once("SIGTERM", shutdown); return; } - const server = serveStdio(createMiftahServerFactory(configPath)); + const server = serveStdio(createMiftahServerFactory(configPath), { + onerror: (error) => { + process.stderr.write(`Miftah STDIO server error: ${redactSecrets(error.message)}\n`); + process.exitCode = 1; + } + }); const shutdown = async () => { await server.close(); }; diff --git a/src/mcp/server/miftah-server.ts b/src/mcp/server/miftah-server.ts index f1f2ea88..f3196329 100644 --- a/src/mcp/server/miftah-server.ts +++ b/src/mcp/server/miftah-server.ts @@ -352,7 +352,8 @@ export class MiftahServer { private readonly oauth?: RemoteOAuthRuntime, identityManager?: IdentityManager, private readonly runtimeConfigPath?: string, - private readonly modernProfileContext?: ModernProfileContextRuntimeOptions + private readonly modernProfileContext?: ModernProfileContextRuntimeOptions, + private readonly resourceSubscriptionsEnabled = true ) { if ( modernProfileContext !== undefined && @@ -584,6 +585,7 @@ export class MiftahServer { private async configureResourceSubscriptionCapability(): Promise { if (this.resourceSubscriptionCapabilityConfigured) return; this.resourceSubscriptionCapabilityConfigured = true; + if (!this.resourceSubscriptionsEnabled) return; if (!this.resourcePromptProxy.available) return; const upstreamNames = this.upstreams instanceof MultiUpstreamProcessManager diff --git a/src/oauth/remote-oauth-client-provider.ts b/src/oauth/remote-oauth-client-provider.ts index 4c18d9b6..47d8af79 100644 --- a/src/oauth/remote-oauth-client-provider.ts +++ b/src/oauth/remote-oauth-client-provider.ts @@ -263,6 +263,7 @@ export class RemoteOAuthClientProvider implements OAuthClientProvider { if (credential.clientId !== undefined) { this.savedClient = { client_id: credential.clientId, + issuer: this.options.binding.issuer, ...(credential.clientSecret === undefined ? {} : { client_secret: credential.clientSecret }) }; } diff --git a/src/runtime/create-miftah-runtime.ts b/src/runtime/create-miftah-runtime.ts index 3949ffc2..43d5b911 100644 --- a/src/runtime/create-miftah-runtime.ts +++ b/src/runtime/create-miftah-runtime.ts @@ -23,6 +23,7 @@ export interface MiftahRuntimeOptions { interface MiftahRuntimeFactoryOptions extends MiftahRuntimeOptions { readonly profileState?: { readonly persistActiveProfile?: false; readonly scope?: "process" | "session" }; + readonly resourceSubscriptionsEnabled?: boolean; } async function createConfiguredMiftahServer( @@ -48,7 +49,8 @@ async function createConfiguredMiftahServer( runtime.oauth, runtime.identities, runtimeConfigPath, - options.modernProfileContext + options.modernProfileContext, + options.resourceSubscriptionsEnabled ); return { config: runtime.config, server }; @@ -100,7 +102,8 @@ export function createMiftahServerFactory( /** Creates per-request modern HTTP servers whose mutable profile state cannot escape an exchange. */ export function createHttpRequestMiftahServerFactory(configPath: string): McpServerFactory { return configuredMiftahServerFactory(configPath, { - profileState: { persistActiveProfile: false, scope: "session" } + profileState: { persistActiveProfile: false, scope: "session" }, + resourceSubscriptionsEnabled: false }); } diff --git a/tests/fixtures/fake-upstream-bundled.mjs b/tests/fixtures/fake-upstream-bundled.mjs index 209a7229..f5a30ed4 100644 --- a/tests/fixtures/fake-upstream-bundled.mjs +++ b/tests/fixtures/fake-upstream-bundled.mjs @@ -7,8 +7,8 @@ var Ig=Object.defineProperty;var $s=(e,t)=>{for(var r in t)Ig(e,r,{get:t[r],enum path: iss.path ? [${w}, ...iss.path] : [${w}] }))); } - - +\x20\x20\x20\x20\x20\x20\x20\x20 +\x20\x20\x20\x20\x20\x20\x20\x20 if (${S}.value === undefined) { if (${w} in input) { newResult[${w}] = undefined; @@ -16,7 +16,7 @@ var Ig=Object.defineProperty;var $s=(e,t)=>{for(var r in t)Ig(e,r,{get:t[r],enum } else { newResult[${w}] = ${S}.value; } - +\x20\x20\x20\x20\x20\x20\x20\x20 `)}R.write("payload.value = newResult;"),R.write("return payload;");let _=R.compile();return(p,S)=>_(z,p,S)},i,a=nr,c=!Ho.jitless,l=c&&Is.value,m=t.catchall,h;e._zod.parse=(z,R)=>{h??(h=n.value);let v=z.value;return a(v)?c&&l&&R?.async===!1&&R.jitless!==!0?(i||(i=o(t.shape)),z=i(z,R),m?zm([],v,z,R,h,e):z):r(z,R):(z.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),z)}});function qd(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!Ct(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>ct(a,n,We())))}),t)}var Vs=q("$ZodUnion",(e,t)=>{ye.init(e,t),Se(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Se(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Se(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Se(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>On(i.source)).join("|")})$`)}});let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let a=!1,c=[];for(let s of t.options){let l=s._zod.run({value:o.value,issues:[]},i);if(l instanceof Promise)c.push(l),a=!0;else{if(l.issues.length===0)return l;c.push(l)}}return a?Promise.all(c).then(s=>qd(s,o,e,i)):qd(c,o,e,i)}});var wm=q("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Vs.init(e,t);let r=e._zod.parse;Se(e._zod,"propValues",()=>{let o={};for(let i of t.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[c,s]of Object.entries(a)){o[c]||(o[c]=new Set);for(let l of s)o[c].add(l)}}return o});let n=Ir(()=>{let o=t.options,i=new Map;for(let a of o){let c=a._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let s of c){if(i.has(s))throw new Error(`Duplicate discriminator value "${String(s)}"`);i.set(s,a)}}return i});e._zod.parse=(o,i)=>{let a=o.value;if(!nr(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;let c=n.value.get(a?.[t.discriminator]);return c?c._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),o)}}),Tm=q("$ZodIntersection",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([s,l])=>Md(r,s,l)):Md(r,i,a)}});function Us(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(xt(e)&&xt(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let a=Us(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n{ye.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!xt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],a=t.keyType._zod.values;if(a){r.value={};let c=new Set;for(let l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){c.add(typeof l=="number"?l.toString():l);let m=t.valueType._zod.run({value:o[l],issues:[]},n);m instanceof Promise?i.push(m.then(h=>{h.issues.length&&r.issues.push(...yt(l,h.issues)),r.value[l]=h.value})):(m.issues.length&&r.issues.push(...yt(l,m.issues)),r.value[l]=m.value)}let s;for(let l in o)c.has(l)||(s=s??[],s.push(l));s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:s})}else{r.value={};for(let c of Reflect.ownKeys(o)){if(c==="__proto__")continue;let s=t.keyType._zod.run({value:c,issues:[]},n);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){t.mode==="loose"?r.value[c]=o[c]:r.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(m=>ct(m,n,We())),input:c,path:[c],inst:e});continue}let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(m=>{m.issues.length&&r.issues.push(...yt(c,m.issues)),r.value[s.value]=m.value})):(l.issues.length&&r.issues.push(...yt(c,l.issues)),r.value[s.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Im=q("$ZodEnum",(e,t)=>{ye.init(e,t);let r=Pn(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>Ps.has(typeof o)).map(o=>typeof o=="string"?ht(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let a=o.value;return n.has(a)||o.issues.push({code:"invalid_value",values:r,input:a,inst:e}),o}}),Pm=q("$ZodLiteral",(e,t)=>{if(ye.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?ht(n):n?ht(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}});var km=q("$ZodTransform",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Tr(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new ft;return r.value=o,r}});function Ud(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Om=q("$ZodOptional",(e,t)=>{ye.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Se(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${On(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Ud(i,r.value)):Ud(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),jm=q("$ZodNullable",(e,t)=>{ye.init(e,t),Se(e._zod,"optin",()=>t.innerType._zod.optin),Se(e._zod,"optout",()=>t.innerType._zod.optout),Se(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${On(r.source)}|null)$`):void 0}),Se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Nm=q("$ZodDefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",Se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Ld(i,t)):Ld(o,t)}});function Ld(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var xm=q("$ZodPrefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",Se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Cm=q("$ZodNonOptional",(e,t)=>{ye.init(e,t),Se(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Dd(i,e)):Dd(o,e)}});function Dd(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Am=q("$ZodCatch",(e,t)=>{ye.init(e,t),Se(e._zod,"optin",()=>t.innerType._zod.optin),Se(e._zod,"optout",()=>t.innerType._zod.optout),Se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(a=>ct(a,n,We()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>ct(i,n,We()))},input:r.value}),r.issues=[]),r)}});var qm=q("$ZodPipe",(e,t)=>{ye.init(e,t),Se(e._zod,"values",()=>t.in._zod.values),Se(e._zod,"optin",()=>t.in._zod.optin),Se(e._zod,"optout",()=>t.out._zod.optout),Se(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);return i instanceof Promise?i.then(a=>Xo(a,t.in,n)):Xo(i,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>Xo(i,t.out,n)):Xo(o,t.out,n)}});function Xo(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var Mm=q("$ZodReadonly",(e,t)=>{ye.init(e,t),Se(e._zod,"propValues",()=>t.innerType._zod.propValues),Se(e._zod,"values",()=>t.innerType._zod.values),Se(e._zod,"optin",()=>t.innerType?._zod?.optin),Se(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Vd):Vd(o)}});function Vd(e){return e.value=Object.freeze(e.value),e}var Um=q("$ZodLazy",(e,t)=>{ye.init(e,t),Se(e._zod,"innerType",()=>t.getter()),Se(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Se(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Se(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Se(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Lm=q("$ZodCustom",(e,t)=>{Ve.init(e,t),ye.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>Zd(i,r,n,e));Zd(o,r,n,e)}});function Zd(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Pr(o))}}var hv=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},gv=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${hv(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ue(n.values[0])}`:`Invalid option: expected one of ${ce(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${ce(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Zs(){return{localeError:gv()}}var Vm;var Fs=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Zm(){return new Fs}(Vm=globalThis).__zod_globalRegistry??(Vm.__zod_globalRegistry=Zm());var bt=globalThis.__zod_globalRegistry;function Fm(e,t){return new e({type:"string",...re(t)})}function Hm(e,t){return new e({type:"string",coerce:!0,...re(t)})}function Hs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...re(t)})}function Js(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...re(t)})}function Jm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...re(t)})}function Bm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(t)})}function Km(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(t)})}function Gm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(t)})}function Bs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function Wm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...re(t)})}function Ym(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(t)})}function Xm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...re(t)})}function Qm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(t)})}function ep(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...re(t)})}function tp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...re(t)})}function rp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(t)})}function np(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(t)})}function op(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(t)})}function ip(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(t)})}function ap(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(t)})}function sp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...re(t)})}function cp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...re(t)})}function up(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...re(t)})}function lp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...re(t)})}function dp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(t)})}function mp(e,t){return new e({type:"string",format:"date",check:"string_format",...re(t)})}function pp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...re(t)})}function fp(e,t){return new e({type:"string",format:"duration",check:"string_format",...re(t)})}function hp(e,t){return new e({type:"number",checks:[],...re(t)})}function gp(e,t){return new e({type:"number",coerce:!0,checks:[],...re(t)})}function vp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function _p(e,t){return new e({type:"boolean",...re(t)})}function Sp(e,t){return new e({type:"boolean",coerce:!0,...re(t)})}function yp(e,t){return new e({type:"bigint",coerce:!0,...re(t)})}function bp(e,t){return new e({type:"null",...re(t)})}function $p(e){return new e({type:"any"})}function zp(e){return new e({type:"unknown"})}function Rp(e,t){return new e({type:"never",...re(t)})}function wp(e,t){return new e({type:"date",coerce:!0,...re(t)})}function kr(e,t){return new qs({check:"less_than",...re(t),value:e,inclusive:!1})}function $t(e,t){return new qs({check:"less_than",...re(t),value:e,inclusive:!0})}function Or(e,t){return new Ms({check:"greater_than",...re(t),value:e,inclusive:!1})}function ut(e,t){return new Ms({check:"greater_than",...re(t),value:e,inclusive:!0})}function Mn(e,t){return new $d({check:"multiple_of",...re(t),value:e})}function Un(e,t){return new Rd({check:"max_length",...re(t),maximum:e})}function or(e,t){return new wd({check:"min_length",...re(t),minimum:e})}function ei(e,t){return new Td({check:"length_equals",...re(t),length:e})}function Ks(e,t){return new Ed({check:"string_format",format:"regex",...re(t),pattern:e})}function Gs(e){return new Id({check:"string_format",format:"lowercase",...re(e)})}function Ws(e){return new Pd({check:"string_format",format:"uppercase",...re(e)})}function Ys(e,t){return new kd({check:"string_format",format:"includes",...re(t),includes:e})}function Xs(e,t){return new Od({check:"string_format",format:"starts_with",...re(t),prefix:e})}function Qs(e,t){return new jd({check:"string_format",format:"ends_with",...re(t),suffix:e})}function At(e){return new Nd({check:"overwrite",tx:e})}function ec(e){return At(t=>t.normalize(e))}function tc(){return At(e=>e.trim())}function rc(){return At(e=>e.toLowerCase())}function nc(){return At(e=>e.toUpperCase())}function oc(){return At(e=>Es(e))}function Tp(e,t,r){return new e({type:"array",element:t,...re(r)})}function Ep(e,t,r){return new e({type:"custom",check:"custom",fn:t,...re(r)})}function Ip(e){let t=bv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Pr(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Pr(o))}},e(r.value,r)));return t}function bv(e,t){let r=new Ve({check:"custom",...re(t)});return r._zod.check=e,r}function jr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??bt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function be(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let m={...r,schemaPath:[...r.schemaPath,e],path:r.path},h=e._zod.parent;if(h)a.ref=h,be(h,t,m),t.seen.get(h).isParent=!0;else if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,m);else{let z=a.schema,R=t.processors[o.type];if(!R)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);R(e,t,z,m)}}let s=t.metadataRegistry.get(e);return s&&Object.assign(a.schema,s),t.io==="input"&&Ye(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Nr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(i[0])?.id,h=e.external.uri??(R=>R);if(m)return{ref:h(m)};let z=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=z,{defId:z,ref:`${h("__shared")}#/${a}/${z}`}}if(i[1]===r)return{ref:"#"};let s=`#/${a}/`,l=i[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:s+l}},o=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:s}=n(i);a.def={...a.schema},s&&(a.defId=s);let l=a.schema;for(let m in l)delete l[m];l.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){o(i);continue}if(e.external){let s=e.external.registry.get(i[0])?.id;if(t!==i[0]&&s){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}if(a.count>1&&e.reused==="ref"){o(i);continue}}}function xr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=e.seen.get(a),s=c.def??c.schema,l={...s};if(c.ref===null)return;let m=c.ref;if(c.ref=null,m){n(m);let h=e.seen.get(m).schema;h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(s.allOf=s.allOf??[],s.allOf.push(h)):(Object.assign(s,h),Object.assign(s,l))}c.isParent||e.override({zodSchema:a,jsonSchema:s,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ln(t,"input"),output:Ln(t,"output")}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ye(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ye(n.element,r);if(n.type==="set")return Ye(n.valueType,r);if(n.type==="lazy")return Ye(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Ye(n.innerType,r);if(n.type==="intersection")return Ye(n.left,r)||Ye(n.right,r);if(n.type==="record"||n.type==="map")return Ye(n.keyType,r)||Ye(n.valueType,r);if(n.type==="pipe")return Ye(n.in,r)||Ye(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ye(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ye(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ye(o,r))return!0;return!!(n.rest&&Ye(n.rest,r))}return!1}var Pp=(e,t={})=>r=>{let n=jr({...r,processors:t});return be(e,n),Nr(n,e),xr(n,e)},Ln=(e,t)=>r=>{let{libraryOptions:n,target:o}=r??{},i=jr({...n??{},target:o,io:t,processors:{}});return be(e,i),Nr(i,e),xr(i,e)};var $v={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ac=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:a,format:c,patterns:s,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof a=="number"&&(o.maxLength=a),c&&(o.format=$v[c]??c,o.format===""&&delete o.format),l&&(o.contentEncoding=l),s&&s.size>0){let m=[...s];m.length===1?o.pattern=m[0].source:m.length>1&&(o.allOf=[...m.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},sc=(e,t,r,n)=>{let o=r,{minimum:i,maximum:a,format:c,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:m}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number",typeof m=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=m,o.exclusiveMinimum=!0):o.exclusiveMinimum=m),typeof i=="number"&&(o.minimum=i,typeof m=="number"&&t.target!=="draft-04"&&(m>=i?delete o.minimum:delete o.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=l,o.exclusiveMaximum=!0):o.exclusiveMaximum=l),typeof a=="number"&&(o.maximum=a,typeof l=="number"&&t.target!=="draft-04"&&(l<=a?delete o.maximum:delete o.exclusiveMaximum)),typeof s=="number"&&(o.multipleOf=s)},cc=(e,t,r,n)=>{r.type="boolean"},uc=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},kp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},lc=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Op=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},jp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},dc=(e,t,r,n)=>{r.not={}},mc=(e,t,r,n)=>{},pc=(e,t,r,n)=>{},fc=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},hc=(e,t,r,n)=>{let o=e._zod.def,i=Pn(o.entries);i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},gc=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let a of o.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Np=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},xp=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Cp=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:c,mime:s}=e._zod.bag;a!==void 0&&(i.minLength=a),c!==void 0&&(i.maxLength=c),s?s.length===1?(i.contentMediaType=s[0],Object.assign(o,i)):o.anyOf=s.map(l=>({...i,contentMediaType:l})):Object.assign(o,i)},Ap=(e,t,r,n)=>{r.type="boolean"},vc=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},qp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},_c=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Mp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Up=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Sc=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:a,maximum:c}=e._zod.bag;typeof a=="number"&&(o.minItems=a),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=be(i.element,t,{...n,path:[...n.path,"items"]})},yc=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let a=i.shape;for(let l in a)o.properties[l]=be(a[l],t,{...n,path:[...n.path,"properties",l]});let c=new Set(Object.keys(a)),s=new Set([...c].filter(l=>{let m=i.shape[l]._zod;return t.io==="input"?m.optin===void 0:m.optout===void 0}));s.size>0&&(o.required=Array.from(s)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=be(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},bc=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,a=o.options.map((c,s)=>be(c,t,{...n,path:[...n.path,i?"oneOf":"anyOf",s]}));i?r.oneOf=a:r.anyOf=a},$c=(e,t,r,n)=>{let o=e._zod.def,i=be(o.left,t,{...n,path:[...n.path,"allOf",0]}),a=be(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,s=[...c(i)?i.allOf:[i],...c(a)?a.allOf:[a]];r.allOf=s},Lp=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",c=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",s=i.items.map((z,R)=>be(z,t,{...n,path:[...n.path,a,R]})),l=i.rest?be(i.rest,t,{...n,path:[...n.path,c,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=s,l&&(o.items=l)):t.target==="openapi-3.0"?(o.items={anyOf:s},l&&o.items.anyOf.push(l),o.minItems=s.length,l||(o.maxItems=s.length)):(o.items=s,l&&(o.additionalItems=l));let{minimum:m,maximum:h}=e._zod.bag;typeof m=="number"&&(o.minItems=m),typeof h=="number"&&(o.maxItems=h)},zc=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=be(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=be(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})},Rc=(e,t,r,n)=>{let o=e._zod.def,i=be(o.innerType,t,n),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},wc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Tc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Ec=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Ic=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},Pc=(e,t,r,n)=>{let o=e._zod.def,i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;be(i,t,n);let a=t.seen.get(e);a.ref=i},kc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},Dp=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Oc=(e,t,r,n)=>{let o=e._zod.def;be(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},jc=(e,t,r,n)=>{let o=e._zod.innerType;be(o,t,n);let i=t.seen.get(e);i.ref=o},ic={string:ac,number:sc,boolean:cc,bigint:uc,symbol:kp,null:lc,undefined:Op,void:jp,never:dc,any:mc,unknown:pc,date:fc,enum:hc,literal:gc,nan:Np,template_literal:xp,file:Cp,success:Ap,custom:vc,function:qp,transform:_c,map:Mp,set:Up,array:Sc,object:yc,union:bc,intersection:$c,tuple:Lp,record:zc,nullable:Rc,nonoptional:wc,default:Tc,prefault:Ec,catch:Ic,pipe:Pc,readonly:kc,promise:Dp,optional:Oc,lazy:jc};function Dn(e,t){if("_idmap"in e){let n=e,o=jr({...t,processors:ic}),i={};for(let s of n._idmap.entries()){let[l,m]=s;be(m,o)}let a={},c={registry:n,uri:t?.uri,defs:i};o.external=c;for(let s of n._idmap.entries()){let[l,m]=s;Nr(o,m),a[l]=xr(o,m)}if(Object.keys(i).length>0){let s=o.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[s]:i}}return{schemas:a}}let r=jr({...t,processors:ic});return be(e,r),Nr(r,e),xr(r,e)}var lt={};$s(lt,{ZodISODate:()=>Cc,ZodISODateTime:()=>Nc,ZodISODuration:()=>Uc,ZodISOTime:()=>qc,date:()=>Ac,datetime:()=>xc,duration:()=>Lc,time:()=>Mc});var Nc=q("ZodISODateTime",(e,t)=>{tm.init(e,t),Ee.init(e,t)});function xc(e){return dp(Nc,e)}var Cc=q("ZodISODate",(e,t)=>{rm.init(e,t),Ee.init(e,t)});function Ac(e){return mp(Cc,e)}var qc=q("ZodISOTime",(e,t)=>{nm.init(e,t),Ee.init(e,t)});function Mc(e){return pp(qc,e)}var Uc=q("ZodISODuration",(e,t)=>{om.init(e,t),Ee.init(e,t)});function Lc(e){return fp(Uc,e)}var Zp=(e,t)=>{Ko.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>xs(e,r)},flatten:{value:r=>Ns(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Er,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Er,2)}},isEmpty:{get(){return e.issues.length===0}}})},y0=q("ZodError",Zp),rt=q("ZodError",Zp,{Parent:Error});var Fp=Go(rt),Hp=Wo(rt),ti=Nn(rt),Jp=xn(rt),Bp=Ml(rt),Kp=Ul(rt),Gp=Ll(rt),Wp=Dl(rt),Yp=Vl(rt),Xp=Zl(rt),Qp=Fl(rt),ef=Hl(rt);var $e=q("ZodType",(e,t)=>(ye.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ln(e,"input"),output:Ln(e,"output")}}),e.toJSONSchema=Pp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(J.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]})),e.clone=(r,n)=>it(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Fp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>ti(e,r,n),e.parseAsync=async(r,n)=>Hp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Jp(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Bp(e,r,n),e.decode=(r,n)=>Kp(e,r,n),e.encodeAsync=async(r,n)=>Gp(e,r,n),e.decodeAsync=async(r,n)=>Wp(e,r,n),e.safeEncode=(r,n)=>Yp(e,r,n),e.safeDecode=(r,n)=>Xp(e,r,n),e.safeEncodeAsync=async(r,n)=>Qp(e,r,n),e.safeDecodeAsync=async(r,n)=>ef(e,r,n),e.refine=(r,n)=>e.check(f_(r,n)),e.superRefine=r=>e.check(h_(r)),e.overwrite=r=>e.check(At(r)),e.optional=()=>Q(e),e.nullable=()=>Vc(e),e.nullish=()=>Q(Vc(e)),e.nonoptional=r=>s_(e,r),e.array=()=>O(e),e.or=r=>W([e,r]),e.and=r=>gt(e,r),e.transform=r=>Zc(e,mf(r)),e.default=r=>o_(e,r),e.prefault=r=>a_(e,r),e.catch=r=>u_(e,r),e.pipe=r=>Zc(e,r),e.readonly=()=>hf(e),e.describe=r=>{let n=e.clone();return bt.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return bt.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return bt.get(e);let n=e.clone();return bt.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),nf=q("_ZodString",(e,t)=>{qn.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>ac(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Ks(...n)),e.includes=(...n)=>e.check(Ys(...n)),e.startsWith=(...n)=>e.check(Xs(...n)),e.endsWith=(...n)=>e.check(Qs(...n)),e.min=(...n)=>e.check(or(...n)),e.max=(...n)=>e.check(Un(...n)),e.length=(...n)=>e.check(ei(...n)),e.nonempty=(...n)=>e.check(or(1,...n)),e.lowercase=n=>e.check(Gs(n)),e.uppercase=n=>e.check(Ws(n)),e.trim=()=>e.check(tc()),e.normalize=(...n)=>e.check(ec(...n)),e.toLowerCase=()=>e.check(rc()),e.toUpperCase=()=>e.check(nc()),e.slugify=()=>e.check(oc())}),Fc=q("ZodString",(e,t)=>{qn.init(e,t),nf.init(e,t),e.email=r=>e.check(Hs(of,r)),e.url=r=>e.check(Bs(af,r)),e.jwt=r=>e.check(lp(Fv,r)),e.emoji=r=>e.check(Wm(kv,r)),e.guid=r=>e.check(Js(tf,r)),e.uuid=r=>e.check(Jm(ri,r)),e.uuidv4=r=>e.check(Bm(ri,r)),e.uuidv6=r=>e.check(Km(ri,r)),e.uuidv7=r=>e.check(Gm(ri,r)),e.nanoid=r=>e.check(Ym(Ov,r)),e.guid=r=>e.check(Js(tf,r)),e.cuid=r=>e.check(Xm(jv,r)),e.cuid2=r=>e.check(Qm(Nv,r)),e.ulid=r=>e.check(ep(xv,r)),e.base64=r=>e.check(sp(Dv,r)),e.base64url=r=>e.check(cp(Vv,r)),e.xid=r=>e.check(tp(Cv,r)),e.ksuid=r=>e.check(rp(Av,r)),e.ipv4=r=>e.check(np(qv,r)),e.ipv6=r=>e.check(op(Mv,r)),e.cidrv4=r=>e.check(ip(Uv,r)),e.cidrv6=r=>e.check(ap(Lv,r)),e.e164=r=>e.check(up(Zv,r)),e.datetime=r=>e.check(xc(r)),e.date=r=>e.check(Ac(r)),e.time=r=>e.check(Mc(r)),e.duration=r=>e.check(Lc(r))});function u(e){return Fm(Fc,e)}var Ee=q("ZodStringFormat",(e,t)=>{we.init(e,t),nf.init(e,t)}),of=q("ZodEmail",(e,t)=>{Jd.init(e,t),Ee.init(e,t)});function Hc(e){return Hs(of,e)}var tf=q("ZodGUID",(e,t)=>{Fd.init(e,t),Ee.init(e,t)});var ri=q("ZodUUID",(e,t)=>{Hd.init(e,t),Ee.init(e,t)});var af=q("ZodURL",(e,t)=>{Bd.init(e,t),Ee.init(e,t)});function Vn(e){return Bs(af,e)}var kv=q("ZodEmoji",(e,t)=>{Kd.init(e,t),Ee.init(e,t)});var Ov=q("ZodNanoID",(e,t)=>{Gd.init(e,t),Ee.init(e,t)});var jv=q("ZodCUID",(e,t)=>{Wd.init(e,t),Ee.init(e,t)});var Nv=q("ZodCUID2",(e,t)=>{Yd.init(e,t),Ee.init(e,t)});var xv=q("ZodULID",(e,t)=>{Xd.init(e,t),Ee.init(e,t)});var Cv=q("ZodXID",(e,t)=>{Qd.init(e,t),Ee.init(e,t)});var Av=q("ZodKSUID",(e,t)=>{em.init(e,t),Ee.init(e,t)});var qv=q("ZodIPv4",(e,t)=>{im.init(e,t),Ee.init(e,t)});var Mv=q("ZodIPv6",(e,t)=>{am.init(e,t),Ee.init(e,t)});var Uv=q("ZodCIDRv4",(e,t)=>{sm.init(e,t),Ee.init(e,t)});var Lv=q("ZodCIDRv6",(e,t)=>{cm.init(e,t),Ee.init(e,t)});var Dv=q("ZodBase64",(e,t)=>{lm.init(e,t),Ee.init(e,t)});var Vv=q("ZodBase64URL",(e,t)=>{dm.init(e,t),Ee.init(e,t)});var Zv=q("ZodE164",(e,t)=>{mm.init(e,t),Ee.init(e,t)});var Fv=q("ZodJWT",(e,t)=>{pm.init(e,t),Ee.init(e,t)});var ni=q("ZodNumber",(e,t)=>{Ls.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>sc(e,n,o,i),e.gt=(n,o)=>e.check(Or(n,o)),e.gte=(n,o)=>e.check(ut(n,o)),e.min=(n,o)=>e.check(ut(n,o)),e.lt=(n,o)=>e.check(kr(n,o)),e.lte=(n,o)=>e.check($t(n,o)),e.max=(n,o)=>e.check($t(n,o)),e.int=n=>e.check(rf(n)),e.safe=n=>e.check(rf(n)),e.positive=n=>e.check(Or(0,n)),e.nonnegative=n=>e.check(ut(0,n)),e.negative=n=>e.check(kr(0,n)),e.nonpositive=n=>e.check($t(0,n)),e.multipleOf=(n,o)=>e.check(Mn(n,o)),e.step=(n,o)=>e.check(Mn(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Z(e){return hp(ni,e)}var Hv=q("ZodNumberFormat",(e,t)=>{fm.init(e,t),ni.init(e,t)});function rf(e){return vp(Hv,e)}var Jc=q("ZodBoolean",(e,t)=>{Ds.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cc(e,r,n,o)});function G(e){return _p(Jc,e)}var sf=q("ZodBigInt",(e,t)=>{hm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>uc(e,n,o,i),e.gte=(n,o)=>e.check(ut(n,o)),e.min=(n,o)=>e.check(ut(n,o)),e.gt=(n,o)=>e.check(Or(n,o)),e.gte=(n,o)=>e.check(ut(n,o)),e.min=(n,o)=>e.check(ut(n,o)),e.lt=(n,o)=>e.check(kr(n,o)),e.lte=(n,o)=>e.check($t(n,o)),e.max=(n,o)=>e.check($t(n,o)),e.positive=n=>e.check(Or(BigInt(0),n)),e.negative=n=>e.check(kr(BigInt(0),n)),e.nonpositive=n=>e.check($t(BigInt(0),n)),e.nonnegative=n=>e.check(ut(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(Mn(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var Jv=q("ZodNull",(e,t)=>{gm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lc(e,r,n,o)});function qt(e){return bp(Jv,e)}var Bv=q("ZodAny",(e,t)=>{vm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mc(e,r,n,o)});function Bc(){return $p(Bv)}var Kv=q("ZodUnknown",(e,t)=>{_m.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pc(e,r,n,o)});function ee(){return zp(Kv)}var Gv=q("ZodNever",(e,t)=>{Sm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dc(e,r,n,o)});function cf(e){return Rp(Gv,e)}var uf=q("ZodDate",(e,t)=>{ym.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>fc(e,n,o,i),e.min=(n,o)=>e.check(ut(n,o)),e.max=(n,o)=>e.check($t(n,o));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var Wv=q("ZodArray",(e,t)=>{bm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Sc(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(or(r,n)),e.nonempty=r=>e.check(or(1,r)),e.max=(r,n)=>e.check(Un(r,n)),e.length=(r,n)=>e.check(ei(r,n)),e.unwrap=()=>e.element});function O(e,t){return Tp(Wv,e,t)}var lf=q("ZodObject",(e,t)=>{Rm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yc(e,r,n,o),J.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>se(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ee()}),e.loose=()=>e.clone({...e._zod.def,catchall:ee()}),e.strict=()=>e.clone({...e._zod.def,catchall:cf()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>J.extend(e,r),e.safeExtend=r=>J.safeExtend(e,r),e.merge=r=>J.merge(e,r),e.pick=r=>J.pick(e,r),e.omit=r=>J.omit(e,r),e.partial=(...r)=>J.partial(pf,e,r[0]),e.required=(...r)=>J.required(ff,e,r[0])});function E(e,t){let r={type:"object",shape:e??{},...J.normalizeParams(t)};return new lf(r)}function ne(e,t){return new lf({type:"object",shape:e,catchall:ee(),...J.normalizeParams(t)})}var df=q("ZodUnion",(e,t)=>{Vs.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bc(e,r,n,o),e.options=t.options});function W(e,t){return new df({type:"union",options:e,...J.normalizeParams(t)})}var Yv=q("ZodDiscriminatedUnion",(e,t)=>{df.init(e,t),wm.init(e,t)});function Cr(e,t,r){return new Yv({type:"union",options:t,discriminator:e,...J.normalizeParams(r)})}var Xv=q("ZodIntersection",(e,t)=>{Tm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$c(e,r,n,o)});function gt(e,t){return new Xv({type:"intersection",left:e,right:t})}var Qv=q("ZodRecord",(e,t)=>{Em.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zc(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function B(e,t,r){return new Qv({type:"record",keyType:e,valueType:t,...J.normalizeParams(r)})}var Dc=q("ZodEnum",(e,t)=>{Im.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(n,o,i)=>hc(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Dc({...t,checks:[],...J.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Dc({...t,checks:[],...J.normalizeParams(o),entries:i})}});function se(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Dc({type:"enum",entries:r,...J.normalizeParams(t)})}var e_=q("ZodLiteral",(e,t)=>{Pm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gc(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function j(e,t){return new e_({type:"literal",values:Array.isArray(e)?e:[e],...J.normalizeParams(t)})}var t_=q("ZodTransform",(e,t)=>{km.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_c(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Tr(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(J.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(J.issue(a))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function mf(e){return new t_({type:"transform",transform:e})}var pf=q("ZodOptional",(e,t)=>{Om.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Oc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Q(e){return new pf({type:"optional",innerType:e})}var r_=q("ZodNullable",(e,t)=>{jm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Rc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Vc(e){return new r_({type:"nullable",innerType:e})}var n_=q("ZodDefault",(e,t)=>{Nm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Tc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function o_(e,t){return new n_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var i_=q("ZodPrefault",(e,t)=>{xm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ec(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function a_(e,t){return new i_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var ff=q("ZodNonOptional",(e,t)=>{Cm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>wc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function s_(e,t){return new ff({type:"nonoptional",innerType:e,...J.normalizeParams(t)})}var c_=q("ZodCatch",(e,t)=>{Am.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ic(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function u_(e,t){return new c_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var l_=q("ZodPipe",(e,t)=>{qm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Pc(e,r,n,o),e.in=t.in,e.out=t.out});function Zc(e,t){return new l_({type:"pipe",in:e,out:t})}var d_=q("ZodReadonly",(e,t)=>{Mm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function hf(e){return new d_({type:"readonly",innerType:e})}var m_=q("ZodLazy",(e,t)=>{Um.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jc(e,r,n,o),e.unwrap=()=>e._zod.def.getter()});function Ar(e){return new m_({type:"lazy",getter:e})}var p_=q("ZodCustom",(e,t)=>{Lm.init(e,t),$e.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vc(e,r,n,o)});function f_(e,t={}){return Ep(p_,e,t)}function h_(e){return Ip(e)}function ar(e,t){return Zc(mf(e),t)}var vf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var gf;gf||(gf={});var oi={};$s(oi,{bigint:()=>y_,boolean:()=>S_,date:()=>b_,number:()=>__,string:()=>v_});function v_(e){return Hm(Fc,e)}function __(e){return gp(ni,e)}function S_(e){return Sp(Jc,e)}function y_(e){return yp(sf,e)}function b_(e){return wp(uf,e)}We(Zs());var cr="2025-11-25";var ii=[cr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ai="io.modelcontextprotocol/related-task",ur="io.modelcontextprotocol/protocolVersion",qr="io.modelcontextprotocol/clientInfo",Rt="io.modelcontextprotocol/serverInfo",wt="io.modelcontextprotocol/clientCapabilities",Zn="io.modelcontextprotocol/subscriptionId",Ut="io.modelcontextprotocol/logLevel";var lr="2.0";var Mt=Ar(()=>W([u(),Z(),G(),qt(),B(u(),Mt),O(Mt)])),ke=B(u(),Mt),Wc=O(Mt),Fn=W([u(),Z().int()]),Hn=u(),si=E({ttl:Z().optional()}),ci=E({taskId:u()}),Jn=ne({progressToken:Fn.optional(),[ai]:ci.optional()}),De=E({_meta:Jn.optional()}),dr=De.extend({task:si.optional()}),Oe=E({method:u(),params:De.loose().optional()}),Be=E({_meta:Jn.optional()}),Ke=E({method:u(),params:Be.loose().optional()}),Bn=ne({get[Rt](){return Lr.optional().catch(void 0)}}),je=ne({_meta:Bn.optional()}),Lt=W([u(),Z().int()]),Kn=E({jsonrpc:j(lr),id:Lt,...Oe.shape}).strict(),Gn=E({jsonrpc:j(lr),...Ke.shape}).strict(),Mr=E({jsonrpc:j(lr),id:Lt,result:je}).strict(),Ur=E({jsonrpc:j(lr),id:Lt.optional(),error:E({code:Z().int(),message:u(),data:ee().optional()})}).strict(),Wn=W([Kn,Gn,Mr,Ur]),Yc=W([Mr,Ur]),Yn=je.strict(),ui=Be.extend({requestId:Lt.optional(),reason:u().optional()}),Xn=Ke.extend({method:j("notifications/cancelled"),params:ui}),li=E({src:u(),mimeType:u().optional(),sizes:O(u()).optional(),theme:se(["light","dark"]).optional()}),Dt=E({icons:O(li).optional()}),zt=E({name:u(),title:u().optional()}),Lr=zt.extend({...zt.shape,...Dt.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),z_=gt(E({applyDefaults:G().optional()}),ke),R_=ar(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,gt(E({form:z_.optional(),url:ke.optional()}),ke.optional())),di=ne({list:ke.optional(),cancel:ke.optional(),requests:ne({sampling:ne({createMessage:ke.optional()}).optional(),elicitation:ne({create:ke.optional()}).optional()}).optional()}),mi=ne({list:ke.optional(),cancel:ke.optional(),requests:ne({tools:ne({call:ke.optional()}).optional()}).optional()}),pi=E({experimental:B(u(),ke).optional(),sampling:E({context:ke.optional(),tools:ke.optional()}).optional(),elicitation:R_.optional(),roots:E({listChanged:G().optional()}).optional(),tasks:di.optional(),extensions:B(u(),ke).optional()}),fi=De.extend({protocolVersion:u(),capabilities:pi,clientInfo:Lr}),hi=Oe.extend({method:j("initialize"),params:fi}),Qn=E({experimental:B(u(),ke).optional(),logging:ke.optional(),completions:ke.optional(),prompts:E({listChanged:G().optional()}).optional(),resources:E({subscribe:G().optional(),listChanged:G().optional()}).optional(),tools:E({listChanged:G().optional()}).optional(),tasks:mi.optional(),extensions:B(u(),ke).optional()}),gi=je.extend({protocolVersion:u(),capabilities:Qn,serverInfo:Lr,instructions:u().optional()}),vi=Ke.extend({method:j("notifications/initialized"),params:Be.optional()}),_i=Oe.extend({method:j("server/discover"),params:De.optional()}),Si=je.extend({supportedVersions:O(u()),capabilities:Qn,instructions:u().optional()}),eo=Oe.extend({method:j("ping"),params:De.optional()}),yi=E({progress:Z(),total:Q(Z()),message:Q(u())}),bi=E({...Be.shape,...yi.shape,progressToken:Fn}),to=Ke.extend({method:j("notifications/progress"),params:bi}),$i=De.extend({cursor:Hn.optional()}),Vt=Oe.extend({params:$i.optional()}),Zt=je.extend({nextCursor:Hn.optional()}),ro=E({uri:u(),mimeType:Q(u()),_meta:B(u(),ee()).optional()}),no=ro.extend({text:u()}),Xc=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),oo=ro.extend({blob:Xc}),Ft=se(["user","assistant"]),Tt=E({audience:O(Ft).optional(),priority:Z().min(0).max(1).optional(),lastModified:lt.datetime({offset:!0}).optional()}),io=E({...zt.shape,...Dt.shape,uri:u(),description:Q(u()),mimeType:Q(u()),size:Q(Z()),annotations:Tt.optional(),_meta:Q(ne({}))}),zi=E({...zt.shape,...Dt.shape,uriTemplate:u(),description:Q(u()),mimeType:Q(u()),annotations:Tt.optional(),_meta:Q(ne({}))}),Ri=Vt.extend({method:j("resources/list")}),wi=Zt.extend({resources:O(io)}),Ti=Vt.extend({method:j("resources/templates/list")}),Ei=Zt.extend({resourceTemplates:O(zi)}),Dr=De.extend({uri:u()}),Ii=Dr,Pi=Oe.extend({method:j("resources/read"),params:Ii}),ki=je.extend({contents:O(W([no,oo]))}),Oi=Ke.extend({method:j("notifications/resources/list_changed"),params:Be.optional()}),ji=Dr,Ni=Oe.extend({method:j("resources/subscribe"),params:ji}),xi=Dr,Ci=Oe.extend({method:j("resources/unsubscribe"),params:xi}),ao=E({toolsListChanged:G().optional(),promptsListChanged:G().optional(),resourcesListChanged:G().optional(),resourceSubscriptions:O(u()).optional()}),Ai=De.extend({notifications:ao}),qi=Oe.extend({method:j("subscriptions/listen"),params:Ai}),Mi=Be.extend({notifications:ao}),Ui=Ke.extend({method:j("notifications/subscriptions/acknowledged"),params:Mi}),Li=Bn.extend({[Zn]:Lt}),Di=je.extend({_meta:Li}),Vi=Be.extend({uri:u()}),Zi=Ke.extend({method:j("notifications/resources/updated"),params:Vi}),Fi=E({name:u(),description:Q(u()),required:Q(G())}),Hi=E({...zt.shape,...Dt.shape,description:Q(u()),arguments:Q(O(Fi)),_meta:Q(ne({}))}),Ji=Vt.extend({method:j("prompts/list")}),Bi=Zt.extend({prompts:O(Hi)}),Ki=De.extend({name:u(),arguments:B(u(),u()).optional()}),Gi=Oe.extend({method:j("prompts/get"),params:Ki}),Vr=E({type:j("text"),text:u(),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Zr=E({type:j("image"),data:Xc,mimeType:u(),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Fr=E({type:j("audio"),data:Xc,mimeType:u(),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Wi=E({type:j("tool_use"),name:u(),id:u(),input:B(u(),ee()),_meta:B(u(),ee()).optional()}),Yi=E({type:j("resource"),resource:W([no,oo]),annotations:Tt.optional(),_meta:B(u(),ee()).optional()}),Xi=io.extend({type:j("resource_link")}),Hr=W([Vr,Zr,Fr,Xi,Yi]),Qi=E({role:Ft,content:Hr}),ea=je.extend({description:u().optional(),messages:O(Qi)}),ta=Ke.extend({method:j("notifications/prompts/list_changed"),params:Be.optional()}),ra=E({title:u().optional(),readOnlyHint:G().optional(),destructiveHint:G().optional(),idempotentHint:G().optional(),openWorldHint:G().optional()}),na=E({taskSupport:se(["required","optional","forbidden"]).optional()}),so=E({...zt.shape,...Dt.shape,description:u().optional(),inputSchema:E({type:j("object"),properties:B(u(),Mt).optional(),required:O(u()).optional()}).catchall(ee()),outputSchema:ne({$schema:u().optional()}).optional(),annotations:ra.optional(),execution:na.optional(),_meta:B(u(),ee()).optional()}),oa=Vt.extend({method:j("tools/list")}),ia=Zt.extend({tools:O(so)}),co=je.extend({content:O(Hr).default([]),structuredContent:ee().optional(),isError:G().optional()}),Qc=co.or(je.extend({toolResult:ee()})),aa=dr.extend({name:u(),arguments:B(u(),ee()).optional()}),sa=Oe.extend({method:j("tools/call"),params:aa}),ca=Ke.extend({method:j("notifications/tools/list_changed"),params:Be.optional()}),eu=E({autoRefresh:G().default(!0),debounceMs:Z().int().nonnegative().default(300)}),Ht=se(["debug","info","notice","warning","error","critical","alert","emergency"]),ua=De.extend({level:Ht}),la=Oe.extend({method:j("logging/setLevel"),params:ua}),da=Be.extend({level:Ht,logger:u().optional(),data:ee()}),ma=Ke.extend({method:j("notifications/message"),params:da}),pa=E({name:u().optional()}),fa=E({hints:O(pa).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),ha=E({mode:se(["auto","required","none"]).optional()}),ga=E({type:j("tool_result"),toolUseId:u().describe("The unique identifier for the corresponding tool call."),content:O(Hr),structuredContent:ee().optional(),isError:G().optional(),_meta:B(u(),ee()).optional()}),va=Cr("type",[Vr,Zr,Fr]),sr=Cr("type",[Vr,Zr,Fr,Wi,ga]),_a=E({role:Ft,content:W([sr,O(sr)]),_meta:B(u(),ee()).optional()}),Sa=dr.extend({messages:O(_a),modelPreferences:fa.optional(),systemPrompt:u().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:O(u()).optional(),metadata:ke.optional(),tools:O(so).optional(),toolChoice:ha.optional()}),ya=Oe.extend({method:j("sampling/createMessage"),params:Sa}),ba=je.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens"]).or(u())),role:Ft,content:va}),$a=je.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens","toolUse"]).or(u())),role:Ft,content:W([sr,O(sr)])}),uo=E({type:j("boolean"),title:u().optional(),description:u().optional(),default:G().optional()}),Jr=E({type:j("string"),title:u().optional(),description:u().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:se(["email","uri","date","date-time"]).optional(),default:u().optional()}),Br=E({type:se(["number","integer"]),title:u().optional(),description:u().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),lo=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),default:u().optional()}),mo=E({type:j("string"),title:u().optional(),description:u().optional(),oneOf:O(E({const:u(),title:u()})),default:u().optional()}),po=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),enumNames:O(u()).optional(),default:u().optional()}),za=W([lo,mo]),fo=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({type:j("string"),enum:O(u())}),default:O(u()).optional()}),ho=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({anyOf:O(E({const:u(),title:u()}))}),default:O(u()).optional()}),Ra=W([fo,ho]),wa=W([po,za,Ra]),go=W([wa,uo,Jr,Br]),Kr=dr.extend({mode:j("form").optional(),message:u(),requestedSchema:E({type:j("object"),properties:B(u(),go),required:O(u()).optional()}).catchall(ee())}),Ta=dr.extend({mode:j("url"),message:u(),elicitationId:u(),url:u().url()}),Ea=W([Kr,Ta]),Ia=Oe.extend({method:j("elicitation/create"),params:Ea}),Pa=Be.extend({elicitationId:u()}),ka=Ke.extend({method:j("notifications/elicitation/complete"),params:Pa}),Oa=je.extend({action:se(["accept","decline","cancel"]),content:ar(e=>e===null?void 0:e,B(u(),W([u(),Z(),G(),O(u())])).optional())}),ja=E({type:j("ref/resource"),uri:u()}),Na=E({type:j("ref/prompt"),name:u()}),xa=De.extend({ref:W([Na,ja]),argument:E({name:u(),value:u()}),context:E({arguments:B(u(),u()).optional()}).optional()}),Ca=Oe.extend({method:j("completion/complete"),params:xa}),Aa=je.extend({completion:ne({values:O(u()).max(100),total:Q(Z().int()),hasMore:Q(G())})}),qa=E({uri:u().startsWith("file://"),name:u().optional(),_meta:B(u(),ee()).optional()}),Ma=Oe.extend({method:j("roots/list"),params:De.optional()}),Ua=je.extend({roots:O(qa)}),La=Ke.extend({method:j("notifications/roots/list_changed"),params:Be.optional()}),tu=ne({ttl:Z().optional(),pollInterval:Z().optional()}),Da=se(["working","input_required","completed","failed","cancelled"]),Jt=E({taskId:u(),status:Da,ttl:W([Z(),qt()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:Q(Z()),statusMessage:Q(u())}),ru=je.extend({task:Jt}),Va=Be.merge(Jt),nu=Ke.extend({method:j("notifications/tasks/status"),params:Va}),ou=Oe.extend({method:j("tasks/get"),params:De.extend({taskId:u()})}),iu=je.merge(Jt),au=Oe.extend({method:j("tasks/result"),params:De.extend({taskId:u()})}),su=je.loose(),cu=Vt.extend({method:j("tasks/list")}),uu=Zt.extend({tasks:O(Jt)}),lu=Oe.extend({method:j("tasks/cancel"),params:De.extend({taskId:u()})}),du=je.merge(Jt),mu=W([eo,hi,_i,Ca,la,Gi,Ji,Ri,Ti,Pi,Ni,Ci,qi,sa,oa]),pu=W([Xn,to,vi,La]),fu=W([Yn,ba,$a,Oa,Ua]),hu=W([eo,ya,Ia,Ma]),gu=W([Xn,to,ma,Zi,Oi,ca,ta,Ui,ka]),vu=W([Yn,gi,Si,Aa,ea,Bi,wi,Ei,ki,co,ia,Di]),Le=Vn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:vf.custom,message:"URL must be parseable",fatal:!0}),zs}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),_u=ne({resource:u().url(),authorization_servers:O(Le).optional(),jwks_uri:u().url().optional(),scopes_supported:O(u()).optional(),bearer_methods_supported:O(u()).optional(),resource_signing_alg_values_supported:O(u()).optional(),resource_name:u().optional(),resource_documentation:u().optional(),resource_policy_uri:u().url().optional(),resource_tos_uri:u().url().optional(),tls_client_certificate_bound_access_tokens:G().optional(),authorization_details_types_supported:O(u()).optional(),dpop_signing_alg_values_supported:O(u()).optional(),dpop_bound_access_tokens_required:G().optional()}),Za=ne({issuer:u(),authorization_endpoint:Le,token_endpoint:Le,registration_endpoint:Le.optional(),scopes_supported:O(u()).optional(),response_types_supported:O(u()),response_modes_supported:O(u()).optional(),grant_types_supported:O(u()).optional(),token_endpoint_auth_methods_supported:O(u()).optional(),token_endpoint_auth_signing_alg_values_supported:O(u()).optional(),service_documentation:Le.optional(),revocation_endpoint:Le.optional(),revocation_endpoint_auth_methods_supported:O(u()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O(u()).optional(),introspection_endpoint:u().optional(),introspection_endpoint_auth_methods_supported:O(u()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O(u()).optional(),code_challenge_methods_supported:O(u()).optional(),client_id_metadata_document_supported:G().optional(),authorization_response_iss_parameter_supported:G().optional().catch(void 0)}),Fa=ne({issuer:u(),authorization_endpoint:Le,token_endpoint:Le,userinfo_endpoint:Le.optional(),jwks_uri:Le,registration_endpoint:Le.optional(),scopes_supported:O(u()).optional(),response_types_supported:O(u()),response_modes_supported:O(u()).optional(),grant_types_supported:O(u()).optional(),acr_values_supported:O(u()).optional(),subject_types_supported:O(u()),id_token_signing_alg_values_supported:O(u()),id_token_encryption_alg_values_supported:O(u()).optional(),id_token_encryption_enc_values_supported:O(u()).optional(),userinfo_signing_alg_values_supported:O(u()).optional(),userinfo_encryption_alg_values_supported:O(u()).optional(),userinfo_encryption_enc_values_supported:O(u()).optional(),request_object_signing_alg_values_supported:O(u()).optional(),request_object_encryption_alg_values_supported:O(u()).optional(),request_object_encryption_enc_values_supported:O(u()).optional(),token_endpoint_auth_methods_supported:O(u()).optional(),token_endpoint_auth_signing_alg_values_supported:O(u()).optional(),display_values_supported:O(u()).optional(),claim_types_supported:O(u()).optional(),claims_supported:O(u()).optional(),service_documentation:u().optional(),claims_locales_supported:O(u()).optional(),ui_locales_supported:O(u()).optional(),claims_parameter_supported:G().optional(),request_parameter_supported:G().optional(),request_uri_parameter_supported:G().optional(),require_request_uri_registration:G().optional(),op_policy_uri:Le.optional(),op_tos_uri:Le.optional(),client_id_metadata_document_supported:G().optional(),authorization_response_iss_parameter_supported:G().optional().catch(void 0)}),Su=E({...Fa.shape,...Za.pick({code_challenge_methods_supported:!0}).shape}),yu=E({access_token:u(),id_token:u().optional(),token_type:u(),expires_in:oi.number().optional(),scope:u().optional(),refresh_token:u().optional()}).strip(),bu=E({issued_token_type:j("urn:ietf:params:oauth:token-type:id-jag"),access_token:u(),token_type:u().optional(),expires_in:Z().optional(),scope:u().optional()}).strip(),$u=E({error:u(),error_description:u().optional(),error_uri:u().optional()}),Gc=Le.optional().or(j("").transform(()=>{})),Ha=E({redirect_uris:O(Le),token_endpoint_auth_method:u().optional(),grant_types:O(u()).optional(),response_types:O(u()).optional(),application_type:u().optional(),client_name:u().optional(),client_uri:Le.optional(),logo_uri:Gc,scope:u().optional(),contacts:O(u()).optional(),tos_uri:Gc,policy_uri:u().optional(),jwks_uri:Le.optional(),jwks:Bc().optional(),software_id:u().optional(),software_version:u().optional(),software_statement:u().optional()}).strip(),Ja=E({client_id:u(),client_secret:u().optional(),client_id_issued_at:Z().optional(),client_secret_expires_at:Z().optional()}).strip(),zu=Ha.merge(Ja),Ru=E({error:u(),error_description:u().optional()}).strip(),wu=E({token:u(),token_type_hint:u().optional()}).strip();var ku=Symbol.for("mcp.sdk.errorBrands");function Cu(e,t){let r=new Set,n=t;for(;typeof n=="function";){let o=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof o=="string"&&r.add(o),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,ku,{value:r,enumerable:!1,configurable:!0})}function Wr(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,ku)){let r=t[ku];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var w_=class Uf extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Wr(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Wr(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",Cu(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new Uf(t.error,t.error_description??t.error,t.error_uri)}},he=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),le=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Wr(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Wr(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",Cu(this,new.target)}},T_=class extends le{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r){super(e,t,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Ef(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function E_(e,t,r){return e==="elicitation"&&t==="form"&&r.form===void 0&&r.url===void 0}function Lf(e){switch(e.method){case"elicitation/create":return e.params?.mode==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function es(e,t){let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=t===void 0?void 0:t[n];if(i===void 0){r[n]=o;continue}if(Ef(o)&&Ef(i)){let a={};for(let[c,s]of Object.entries(o))s!==void 0&&i[c]===void 0&&!E_(n,c,i)&&(a[c]=s);Object.keys(a).length>0&&(r[n]=a)}}return Object.keys(r).length>0?r:void 0}var I_="2026-07-28";function $o(e){return e>=I_}function Df(e){return e.filter(t=>!$o(t))}function Au(e){return e.filter(t=>$o(t))}function Vf(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Zf=["task","inputRequests","requestState"];function qu(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Zf.some(t=>t in e)?e:{...e,content:[]}}function P_(){let e=Ar(()=>W([u(),Z(),G(),qt(),B(u(),e),O(e)])),t=B(u(),e),r=W([u(),Z().int()]),n=u(),o=E({ttl:Z().optional()}),i=E({taskId:u()}),a=ne({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=E({_meta:a.optional()}),s=c.extend({task:o.optional()}),l=E({method:u(),params:c.loose().optional()}),m=E({_meta:a.optional()}),h=E({method:u(),params:m.loose().optional()}),z=ne({_meta:a.optional()}),R=W([u(),Z().int()]),v=z.strict(),b=m.extend({requestId:R.optional(),reason:u().optional()}),g=h.extend({method:j("notifications/cancelled"),params:b}),d=E({src:u(),mimeType:u().optional(),sizes:O(u()).optional(),theme:se(["light","dark"]).optional()}),_=E({icons:O(d).optional()}),p=E({name:u(),title:u().optional()}),S=p.extend({...p.shape,..._.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),w=gt(E({applyDefaults:G().optional()}),t),y=ar(Je=>Je&&typeof Je=="object"&&!Array.isArray(Je)&&Object.keys(Je).length===0?{form:{}}:Je,gt(E({form:w.optional(),url:t.optional()}),t.optional())),f=ne({list:t.optional(),cancel:t.optional(),requests:ne({sampling:ne({createMessage:t.optional()}).optional(),elicitation:ne({create:t.optional()}).optional()}).optional()}),T=ne({list:t.optional(),cancel:t.optional(),requests:ne({tools:ne({call:t.optional()}).optional()}).optional()}),A=E({experimental:B(u(),t).optional(),sampling:E({context:t.optional(),tools:t.optional()}).optional(),elicitation:y.optional(),roots:E({listChanged:G().optional()}).optional(),tasks:f.optional(),extensions:B(u(),t).optional()}),F=c.extend({protocolVersion:u(),capabilities:A,clientInfo:S}),M=l.extend({method:j("initialize"),params:F}),D=E({experimental:B(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:E({listChanged:G().optional()}).optional(),resources:E({subscribe:G().optional(),listChanged:G().optional()}).optional(),tools:E({listChanged:G().optional()}).optional(),tasks:T.optional(),extensions:B(u(),t).optional()}),Y=z.extend({protocolVersion:u(),capabilities:D,serverInfo:S,instructions:u().optional()}),K=h.extend({method:j("notifications/initialized"),params:m.optional()}),fe=l.extend({method:j("ping"),params:c.optional()}),Te=E({progress:Z(),total:Q(Z()),message:Q(u())}),ze=E({...m.shape,...Te.shape,progressToken:r}),Ce=h.extend({method:j("notifications/progress"),params:ze}),ve=c.extend({cursor:n.optional()}),k=l.extend({params:ve.optional()}),x=z.extend({nextCursor:n.optional()}),V=E({uri:u(),mimeType:Q(u()),_meta:B(u(),ee()).optional()}),$=V.extend({text:u()}),P=u().refine(Je=>{try{return atob(Je),!0}catch{return!1}},{message:"Invalid Base64 string"}),N=V.extend({blob:P}),H=se(["user","assistant"]),te=E({audience:O(H).optional(),priority:Z().min(0).max(1).optional(),lastModified:lt.datetime({offset:!0}).optional()}),pe=E({...p.shape,..._.shape,uri:u(),description:Q(u()),mimeType:Q(u()),size:Q(Z()),annotations:te.optional(),_meta:Q(ne({}))}),ae=E({...p.shape,..._.shape,uriTemplate:u(),description:Q(u()),mimeType:Q(u()),annotations:te.optional(),_meta:Q(ne({}))}),Re=k.extend({method:j("resources/list")}),Ge=x.extend({resources:O(pe)}),I=k.extend({method:j("resources/templates/list")}),C=x.extend({resourceTemplates:O(ae)}),U=c.extend({uri:u()}),oe=U,ie=l.extend({method:j("resources/read"),params:oe}),me=z.extend({contents:O(W([$,N]))}),Ne=h.extend({method:j("notifications/resources/list_changed"),params:m.optional()}),qe=U,Fe=l.extend({method:j("resources/subscribe"),params:qe}),Ae=U,Ie=l.extend({method:j("resources/unsubscribe"),params:Ae}),nt=m.extend({uri:u()}),Ue=h.extend({method:j("notifications/resources/updated"),params:nt}),_t=E({name:u(),description:Q(u()),required:Q(G())}),at=E({...p.shape,..._.shape,description:Q(u()),arguments:Q(O(_t)),_meta:Q(ne({}))}),St=k.extend({method:j("prompts/list")}),Et=x.extend({prompts:O(at)}),It=c.extend({name:u(),arguments:B(u(),u()).optional()}),Bt=l.extend({method:j("prompts/get"),params:It}),Kt=E({type:j("text"),text:u(),annotations:te.optional(),_meta:B(u(),ee()).optional()}),Gt=E({type:j("image"),data:P,mimeType:u(),annotations:te.optional(),_meta:B(u(),ee()).optional()}),Wt=E({type:j("audio"),data:P,mimeType:u(),annotations:te.optional(),_meta:B(u(),ee()).optional()}),en=E({type:j("tool_use"),name:u(),id:u(),input:B(u(),ee()),_meta:B(u(),ee()).optional()}),Pt=E({type:j("resource"),resource:W([$,N]),annotations:te.optional(),_meta:B(u(),ee()).optional()}),tn=pe.extend({type:j("resource_link")}),ot=W([Kt,Gt,Wt,tn,Pt]),hr=E({role:H,content:ot}),gr=z.extend({description:u().optional(),messages:O(hr)}),Yt=h.extend({method:j("notifications/prompts/list_changed"),params:m.optional()}),rn=E({title:u().optional(),readOnlyHint:G().optional(),destructiveHint:G().optional(),idempotentHint:G().optional(),openWorldHint:G().optional()}),vr=E({taskSupport:se(["required","optional","forbidden"]).optional()}),Xt=E({...p.shape,..._.shape,description:u().optional(),inputSchema:E({type:j("object"),properties:B(u(),e).optional(),required:O(u()).optional()}).catchall(ee()),outputSchema:E({type:j("object"),properties:B(u(),e).optional(),required:O(u()).optional()}).catchall(ee()).optional(),annotations:rn.optional(),execution:vr.optional(),_meta:B(u(),ee()).optional()}),_r=k.extend({method:j("tools/list")}),Sr=x.extend({tools:O(Xt)}),yr=z.extend({content:O(ot),structuredContent:B(u(),ee()).optional(),isError:G().optional()}),He=s.extend({name:u(),arguments:B(u(),ee()).optional()}),nn=l.extend({method:j("tools/call"),params:He}),To=h.extend({method:j("notifications/tools/list_changed"),params:m.optional()}),br=se(["debug","info","notice","warning","error","critical","alert","emergency"]),on=c.extend({level:br}),an=l.extend({method:j("logging/setLevel"),params:on}),sn=m.extend({level:br,logger:u().optional(),data:ee()}),cn=h.extend({method:j("notifications/message"),params:sn}),un=E({name:u().optional()}),ln=E({hints:O(un).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),dn=E({mode:se(["auto","required","none"]).optional()}),Eo=E({type:j("tool_result"),toolUseId:u().describe("The unique identifier for the corresponding tool call."),content:O(ot),structuredContent:E({}).loose().optional(),isError:G().optional(),_meta:B(u(),ee()).optional()}),mn=Cr("type",[Kt,Gt,Wt]),kt=Cr("type",[Kt,Gt,Wt,en,Eo]),pn=E({role:H,content:W([kt,O(kt)]),_meta:B(u(),ee()).optional()}),fn=s.extend({messages:O(pn),modelPreferences:ln.optional(),systemPrompt:u().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:O(u()).optional(),metadata:t.optional(),tools:O(Xt).optional(),toolChoice:dn.optional()}),hn=l.extend({method:j("sampling/createMessage"),params:fn}),gn=z.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens"]).or(u())),role:H,content:mn}),vn=z.extend({model:u(),stopReason:Q(se(["endTurn","stopSequence","maxTokens","toolUse"]).or(u())),role:H,content:W([kt,O(kt)])}),_n=E({type:j("boolean"),title:u().optional(),description:u().optional(),default:G().optional()}),Sn=E({type:j("string"),title:u().optional(),description:u().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:se(["email","uri","date","date-time"]).optional(),default:u().optional()}),yn=E({type:se(["number","integer"]),title:u().optional(),description:u().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),bn=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),default:u().optional()}),$n=E({type:j("string"),title:u().optional(),description:u().optional(),oneOf:O(E({const:u(),title:u()})),default:u().optional()}),zn=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),enumNames:O(u()).optional(),default:u().optional()}),Rn=W([bn,$n]),Qt=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({type:j("string"),enum:O(u())}),default:O(u()).optional()}),er=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({anyOf:O(E({const:u(),title:u()}))}),default:O(u()).optional()}),Io=W([Qt,er]),Po=W([zn,Rn,Io]),et=W([Po,_n,Sn,yn]),tt=s.extend({mode:j("form").optional(),message:u(),requestedSchema:E({type:j("object"),properties:B(u(),et),required:O(u()).optional()}).catchall(ee())}),wn=s.extend({mode:j("url"),message:u(),elicitationId:u(),url:u().url()}),st=W([tt,wn]),ko=l.extend({method:j("elicitation/create"),params:st}),Oo=m.extend({elicitationId:u()}),jo=h.extend({method:j("notifications/elicitation/complete"),params:Oo}),No=z.extend({action:se(["accept","decline","cancel"]),content:ar(Je=>Je===null?void 0:Je,B(u(),W([u(),Z(),G(),O(u())])).optional())}),xo=E({type:j("ref/resource"),uri:u()}),Co=E({type:j("ref/prompt"),name:u()}),Ao=c.extend({ref:W([Co,xo]),argument:E({name:u(),value:u()}),context:E({arguments:B(u(),u()).optional()}).optional()}),Tn=l.extend({method:j("completion/complete"),params:Ao}),qo=z.extend({completion:ne({values:O(u()).max(100),total:Q(Z().int()),hasMore:Q(G())})}),Mo=E({uri:u().startsWith("file://"),name:u().optional(),_meta:B(u(),ee()).optional()}),$r=l.extend({method:j("roots/list"),params:c.optional()}),En=z.extend({roots:O(Mo)}),Uo=h.extend({method:j("notifications/roots/list_changed"),params:m.optional()}),Lo=ne({ttl:Z().optional(),pollInterval:Z().optional()}),Do=se(["working","input_required","completed","failed","cancelled"]),Ot=E({taskId:u(),status:Do,ttl:W([Z(),qt()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:Q(Z()),statusMessage:Q(u())}),Xe=z.extend({task:Ot}),Vo=m.merge(Ot),tr=h.extend({method:j("notifications/tasks/status"),params:Vo}),zr=l.extend({method:j("tasks/get"),params:c.extend({taskId:u()})}),Rr=z.merge(Ot),wr=l.extend({method:j("tasks/result"),params:c.extend({taskId:u()})}),bs=z.loose(),Qe=k.extend({method:j("tasks/list")}),xe=x.extend({tasks:O(Ot)}),rr=l.extend({method:j("tasks/cancel"),params:c.extend({taskId:u()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:o,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:s,RequestSchema:l,NotificationsParamsSchema:m,NotificationSchema:h,ResultSchema:z,RequestIdSchema:R,EmptyResultSchema:v,CancelledNotificationParamsSchema:b,CancelledNotificationSchema:g,IconSchema:d,IconsSchema:_,BaseMetadataSchema:p,ImplementationSchema:S,ClientTasksCapabilitySchema:f,ServerTasksCapabilitySchema:T,ClientCapabilitiesSchema:A,InitializeRequestParamsSchema:F,InitializeRequestSchema:M,ServerCapabilitiesSchema:D,InitializeResultSchema:Y,InitializedNotificationSchema:K,PingRequestSchema:fe,ProgressSchema:Te,ProgressNotificationParamsSchema:ze,ProgressNotificationSchema:Ce,PaginatedRequestParamsSchema:ve,PaginatedRequestSchema:k,PaginatedResultSchema:x,ResourceContentsSchema:V,TextResourceContentsSchema:$,BlobResourceContentsSchema:N,RoleSchema:H,AnnotationsSchema:te,ResourceSchema:pe,ResourceTemplateSchema:ae,ListResourcesRequestSchema:Re,ListResourcesResultSchema:Ge,ListResourceTemplatesRequestSchema:I,ListResourceTemplatesResultSchema:C,ResourceRequestParamsSchema:U,ReadResourceRequestParamsSchema:oe,ReadResourceRequestSchema:ie,ReadResourceResultSchema:me,ResourceListChangedNotificationSchema:Ne,SubscribeRequestParamsSchema:qe,SubscribeRequestSchema:Fe,UnsubscribeRequestParamsSchema:Ae,UnsubscribeRequestSchema:Ie,ResourceUpdatedNotificationParamsSchema:nt,ResourceUpdatedNotificationSchema:Ue,PromptArgumentSchema:_t,PromptSchema:at,ListPromptsRequestSchema:St,ListPromptsResultSchema:Et,GetPromptRequestParamsSchema:It,GetPromptRequestSchema:Bt,TextContentSchema:Kt,ImageContentSchema:Gt,AudioContentSchema:Wt,ToolUseContentSchema:en,EmbeddedResourceSchema:Pt,ResourceLinkSchema:tn,ContentBlockSchema:ot,PromptMessageSchema:hr,GetPromptResultSchema:gr,PromptListChangedNotificationSchema:Yt,ToolAnnotationsSchema:rn,ToolExecutionSchema:vr,ToolSchema:Xt,ListToolsRequestSchema:_r,ListToolsResultSchema:Sr,CallToolResultSchema:yr,CallToolRequestParamsSchema:He,CallToolRequestSchema:nn,ToolListChangedNotificationSchema:To,LoggingLevelSchema:br,SetLevelRequestParamsSchema:on,SetLevelRequestSchema:an,LoggingMessageNotificationParamsSchema:sn,LoggingMessageNotificationSchema:cn,ModelHintSchema:un,ModelPreferencesSchema:ln,ToolChoiceSchema:dn,ToolResultContentSchema:Eo,SamplingContentSchema:mn,SamplingMessageContentBlockSchema:kt,SamplingMessageSchema:pn,CreateMessageRequestParamsSchema:fn,CreateMessageRequestSchema:hn,CreateMessageResultSchema:gn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:_n,StringSchemaSchema:Sn,NumberSchemaSchema:yn,UntitledSingleSelectEnumSchemaSchema:bn,TitledSingleSelectEnumSchemaSchema:$n,LegacyTitledEnumSchemaSchema:zn,SingleSelectEnumSchemaSchema:Rn,UntitledMultiSelectEnumSchemaSchema:Qt,TitledMultiSelectEnumSchemaSchema:er,MultiSelectEnumSchemaSchema:Io,EnumSchemaSchema:Po,PrimitiveSchemaDefinitionSchema:et,ElicitRequestFormParamsSchema:tt,ElicitRequestURLParamsSchema:wn,ElicitRequestParamsSchema:st,ElicitRequestSchema:ko,ElicitationCompleteNotificationParamsSchema:Oo,ElicitationCompleteNotificationSchema:jo,ElicitResultSchema:No,ResourceTemplateReferenceSchema:xo,PromptReferenceSchema:Co,CompleteRequestParamsSchema:Ao,CompleteRequestSchema:Tn,CompleteResultSchema:qo,RootSchema:Mo,ListRootsRequestSchema:$r,ListRootsResultSchema:En,RootsListChangedNotificationSchema:Uo,TaskCreationParamsSchema:Lo,TaskStatusSchema:Do,TaskSchema:Ot,CreateTaskResultSchema:Xe,TaskStatusNotificationParamsSchema:Vo,TaskStatusNotificationSchema:tr,GetTaskRequestSchema:zr,GetTaskResultSchema:Rr,GetTaskPayloadRequestSchema:wr,GetTaskPayloadResultSchema:bs,ListTasksRequestSchema:Qe,ListTasksResultSchema:xe,CancelTaskRequestSchema:rr,CancelTaskResultSchema:z.merge(Ot),ClientRequestSchema:W([fe,M,Tn,an,Bt,St,Re,I,ie,Fe,Ie,nn,_r,zr,wr,Qe,rr]),ClientNotificationSchema:W([g,Ce,K,Uo,tr]),ClientResultSchema:W([v,gn,vn,No,En,Rr,xe,Xe]),ServerRequestSchema:W([fe,hn,ko,$r,zr,wr,Qe,rr]),ServerNotificationSchema:W([g,Ce,cn,Ue,Ne,To,Yt,tr,jo]),ServerResultSchema:W([v,Y,qo,gr,Et,Ge,C,me,yr,Sr,Rr,xe,Xe]),CallToolResultWireSchema:ee().superRefine((Je,Eg)=>{if(!(typeof Je!="object"||Je===null||Array.isArray(Je)||Je.content!==void 0)){for(let zl of Zf)if(zl in Je){Eg.addIssue({code:"custom",message:`content is required when the body carries '${zl}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(qu).pipe(yr)}}var k_;function Ff(){return k_??=P_()}function Hf(e){return e.type!=="object"}var O_=new Set(["const","enum","default","examples"]),j_=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function If(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function N_(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(If(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Tl(e.$schema)&&e.$recursiveAnchor!==!0,n=(o,i)=>{if(Array.isArray(o))return o.map(s=>n(s,!1));if(o===null||typeof o!="object"||!i&&If(o.$id))return o;let a={},c=!1;for(let[s,l]of Object.entries(o))i?a[s]=n(l,!1):(s==="$ref"||s==="$dynamicRef")&&typeof l=="string"?a[s]=l==="#"?"#/properties/result":l.startsWith("#/")?`#/properties/result${l.slice(1)}`:l:s==="$recursiveRef"&&l==="#"&&r?c=!0:O_.has(s)?a[s]=l:j_.has(s)?a[s]=n(l,!0):a[s]=n(l,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}var Jf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Bf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},x_={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ba;function Mu(){if(Ba)return Ba;let e=Ff();return Ba={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Ba}function Kf(e){return Object.prototype.hasOwnProperty.call(Jf,e)}function Gf(e){return Object.prototype.hasOwnProperty.call(Bf,e)}function C_(e){return Object.prototype.hasOwnProperty.call(x_,e)}function A_(e){return C_(e)?Mu().resultSchemas[e]:void 0}function q_(e){return Kf(e)?Mu().requestSchemas[e]:void 0}function M_(e){return Gf(e)?Mu().notificationSchemas[e]:void 0}var nT=Object.keys(Jf),oT=Object.keys(Bf);function Ou(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ka(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Pf={ok:!1,reason:"not-in-era"};function kf(e){return Ou(e)&&Ou(e.outputSchema)&&Hf(e.outputSchema)}var Uu={era:"2025-11-25",hasRequestMethod:Kf,hasNotificationMethod:Gf,validateRequest:(e,t)=>Ka(q_(e),t),validateResult:(e,t)=>Ka(A_(e),t),validateNotification:(e,t)=>Ka(M_(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Pf,validateInputResponse:()=>Pf,samplingResultVariant:((e,t)=>{let r=Ff();return Ka(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let r=Vf(e),n=r.structuredContent;if(n===void 0)return r;let o=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&Hf(t);return!o&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Ou(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>kf(n))?t:{...t,tools:r.map(n=>kf(n)?{...n,outputSchema:N_(n.outputSchema)}:n)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function U_(){let e=Ar(()=>W([u(),Z(),G(),qt(),B(u(),e),O(e)])),t=B(u(),e),r=W([u(),Z().int()]),n=u(),o=W([u(),Z().int()]),i=se(["user","assistant"]),a=se(["debug","info","notice","warning","error","critical","alert","emergency"]),c=u().refine(xe=>{try{return atob(xe),!0}catch{return!1}},{message:"Invalid Base64 string"}),s=E({ttl:Z().optional()}),l=E({taskId:u()}),m=ne({progressToken:r.optional(),"io.modelcontextprotocol/related-task":l.optional()}),h=E({_meta:m.optional()}),z=h.extend({task:s.optional()}),R=E({_meta:m.optional()}),v=E({method:u(),params:R.loose().optional()}),b=E({src:u(),mimeType:u().optional(),sizes:O(u()).optional(),theme:se(["light","dark"]).optional()}),g=E({icons:O(b).optional()}),d=E({name:u(),title:u().optional()}),_=d.extend({...d.shape,...g.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),p=gt(E({applyDefaults:G().optional()}),t),S=ar(xe=>xe&&typeof xe=="object"&&!Array.isArray(xe)&&Object.keys(xe).length===0?{form:{}}:xe,gt(E({form:p.optional(),url:t.optional()}),t.optional())),w=ne({list:t.optional(),cancel:t.optional(),requests:ne({sampling:ne({createMessage:t.optional()}).optional(),elicitation:ne({create:t.optional()}).optional()}).optional()}),y=ne({list:t.optional(),cancel:t.optional(),requests:ne({tools:ne({call:t.optional()}).optional()}).optional()}),f=E({experimental:B(u(),t).optional(),sampling:E({context:t.optional(),tools:t.optional()}).optional(),elicitation:S.optional(),roots:E({listChanged:G().optional()}).optional(),tasks:w.optional(),extensions:B(u(),t).optional()}),T=E({experimental:B(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:E({listChanged:G().optional()}).optional(),resources:E({subscribe:G().optional(),listChanged:G().optional()}).optional(),tools:E({listChanged:G().optional()}).optional(),tasks:y.optional(),extensions:B(u(),t).optional()}),A=E({progress:Z(),total:Q(Z()),message:Q(u())}),F=E({...R.shape,...A.shape,progressToken:r}),M=v.extend({method:j("notifications/progress"),params:F}),D=R.extend({level:a,logger:u().optional(),data:ee()}),Y=v.extend({method:j("notifications/message"),params:D}),K=E({uri:u(),mimeType:Q(u()),_meta:B(u(),ee()).optional()}),fe=K.extend({text:u()}),Te=K.extend({blob:c}),ze=E({audience:O(i).optional(),priority:Z().min(0).max(1).optional(),lastModified:lt.datetime({offset:!0}).optional()}),Ce=E({...d.shape,...g.shape,uri:u(),description:Q(u()),mimeType:Q(u()),size:Q(Z()),annotations:ze.optional(),_meta:Q(ne({}))}),ve=E({...d.shape,...g.shape,uriTemplate:u(),description:Q(u()),mimeType:Q(u()),annotations:ze.optional(),_meta:Q(ne({}))}),k=v.extend({method:j("notifications/resources/list_changed"),params:R.optional()}),x=R.extend({uri:u()}),V=v.extend({method:j("notifications/resources/updated"),params:x}),$=E({name:u(),description:Q(u()),required:Q(G())}),P=E({...d.shape,...g.shape,description:Q(u()),arguments:Q(O($)),_meta:Q(ne({}))}),N=v.extend({method:j("notifications/prompts/list_changed"),params:R.optional()}),H=E({type:j("text"),text:u(),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),te=E({type:j("image"),data:c,mimeType:u(),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),pe=E({type:j("audio"),data:c,mimeType:u(),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),ae=E({type:j("tool_use"),name:u(),id:u(),input:B(u(),ee()),_meta:B(u(),ee()).optional()}),Re=E({type:j("resource"),resource:W([fe,Te]),annotations:ze.optional(),_meta:B(u(),ee()).optional()}),Ge=Ce.extend({type:j("resource_link")}),I=W([H,te,pe,Ge,Re]),C=E({role:i,content:I}),U=E({title:u().optional(),readOnlyHint:G().optional(),destructiveHint:G().optional(),idempotentHint:G().optional(),openWorldHint:G().optional()}),oe=v.extend({method:j("notifications/tools/list_changed"),params:R.optional()}),ie=E({name:u().optional()}),me=E({hints:O(ie).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),Ne=E({mode:se(["auto","required","none"]).optional()}),qe=E({type:j("boolean"),title:u().optional(),description:u().optional(),default:G().optional()}),Fe=E({type:j("string"),title:u().optional(),description:u().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:se(["email","uri","date","date-time"]).optional(),default:u().optional()}),Ae=E({type:se(["number","integer"]),title:u().optional(),description:u().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),Ie=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),default:u().optional()}),nt=E({type:j("string"),title:u().optional(),description:u().optional(),oneOf:O(E({const:u(),title:u()})),default:u().optional()}),Ue=E({type:j("string"),title:u().optional(),description:u().optional(),enum:O(u()),enumNames:O(u()).optional(),default:u().optional()}),_t=W([Ie,nt]),at=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({type:j("string"),enum:O(u())}),default:O(u()).optional()}),St=E({type:j("array"),title:u().optional(),description:u().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:E({anyOf:O(E({const:u(),title:u()}))}),default:O(u()).optional()}),Et=W([at,St]),It=W([Ue,_t,Et]),Bt=W([It,qe,Fe,Ae]),Kt=z.extend({mode:j("form").optional(),message:u(),requestedSchema:E({type:j("object"),properties:B(u(),Bt),required:O(u()).optional()}).catchall(ee())}),Gt=E({type:j("ref/resource"),uri:u()}),Wt=E({type:j("ref/prompt"),name:u()}),en=E({uri:u().startsWith("file://"),name:u().optional(),_meta:B(u(),ee()).optional()}),Pt=f.shape,tn=E({experimental:Pt.experimental,sampling:Pt.sampling,elicitation:Pt.elicitation,roots:Pt.roots,extensions:Pt.extensions}),ot=T.shape,hr=E({experimental:ot.experimental,logging:ot.logging,completions:ot.completions,prompts:ot.prompts,resources:ot.resources,tools:ot.tools,extensions:ot.extensions}),gr=ne({progressToken:r.optional(),[ur]:u(),[qr]:_.optional(),[wt]:tn,[Ut]:a.optional()}),Yt=E({...d.shape,...g.shape,description:u().optional(),inputSchema:ne({$schema:u().optional(),type:j("object")}),outputSchema:ne({$schema:u().optional()}).optional(),annotations:U.optional(),_meta:B(u(),ee()).optional()}),rn=E({type:j("tool_result"),toolUseId:u(),content:O(I),structuredContent:ee().optional(),isError:G().optional(),_meta:B(u(),ee()).optional()}),vr=W([H,te,pe,ae,rn]),Xt=E({role:i,content:W([vr,O(vr)]),_meta:B(u(),ee()).optional()}),_r=u(),Sr=ne({[Rt]:_.optional().catch(void 0)}),yr=Sr.optional();function He(xe){return ne({_meta:yr,resultType:_r.default("complete"),...xe})}let nn=He({}),To=He({nextCursor:n.optional()}),br=He({content:O(I),structuredContent:ee().optional(),isError:G().optional()}),on=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),tools:O(Yt),nextCursor:n.optional()}),an=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),prompts:O(P),nextCursor:n.optional()}),sn=He({description:u().optional(),messages:O(C)}),cn=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resources:O(Ce),nextCursor:n.optional()}),un=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resourceTemplates:O(ve),nextCursor:n.optional()}),ln=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),contents:O(W([fe,Te]))}),dn=He({completion:E({values:O(u()).max(100),total:Z().int().optional(),hasMore:G().optional()}).loose()}),Eo=He({ttlMs:Z().int().min(0),cacheScope:se(["public","private"])}),mn=He({ttlMs:Z().int().min(0).catch(0),cacheScope:se(["public","private"]).catch("private"),supportedVersions:O(u()),capabilities:hr,instructions:u().optional()}),kt=E({messages:O(Xt),modelPreferences:me.optional(),systemPrompt:u().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:O(u()).optional(),metadata:t.optional(),tools:O(Yt).optional(),toolChoice:Ne.optional()}),pn=E({method:j("sampling/createMessage"),params:kt}),fn=E({method:j("roots/list"),params:E({_meta:B(u(),ee()).optional()}).optional()}),hn=E({...Xt.shape,model:u(),stopReason:u().optional()}),gn=E({roots:O(en)}),vn=E({action:se(["accept","decline","cancel"]),content:B(u(),W([u(),Z(),G(),O(u())])).optional()}),_n=E({mode:j("url"),message:u(),url:u().url()}),Sn=W([Kt,_n]),yn=E({method:j("elicitation/create"),params:Sn}),bn=W([pn,fn,yn]),$n=W([hn,gn,vn]),zn=B(u(),bn),Rn=B(u(),$n),Qt=He({inputRequests:zn.optional(),requestState:u().optional()}),er={inputResponses:Rn.optional(),requestState:u().optional()},Io=E({_meta:gr,...er}),Po=ne({progressToken:r.optional()});function et(xe,rr){return E({method:j(xe),params:E({_meta:gr,...rr})})}function tt(xe,rr){return E({method:j(xe),params:E({_meta:Po.optional(),...rr}).optional()})}let wn={name:u(),arguments:B(u(),ee()).optional(),...er},st={cursor:n.optional()},ko=et("tools/call",wn),Oo=et("tools/list",st),jo=et("prompts/list",st),No=et("prompts/get",{name:u(),arguments:B(u(),u()).optional(),...er}),xo=et("resources/list",st),Co=et("resources/templates/list",st),Ao=et("resources/read",{uri:u(),...er}),Tn={ref:W([Wt,Gt]),argument:E({name:u(),value:u()}),context:E({arguments:B(u(),u()).optional()}).optional()},qo=et("completion/complete",Tn),Mo=et("server/discover",{}),$r=E({toolsListChanged:G().optional(),promptsListChanged:G().optional(),resourcesListChanged:G().optional(),resourceSubscriptions:O(u()).optional()}),En={notifications:$r},Uo=et("subscriptions/listen",En),Lo=Sr.extend({"io.modelcontextprotocol/subscriptionId":o}),Do=ne({_meta:Lo,resultType:_r.default("complete")}),Ot={"tools/call":tt("tools/call",wn),"tools/list":tt("tools/list",st),"prompts/get":tt("prompts/get",{name:u(),arguments:B(u(),u()).optional()}),"prompts/list":tt("prompts/list",st),"resources/list":tt("resources/list",st),"resources/templates/list":tt("resources/templates/list",st),"resources/read":tt("resources/read",{uri:u()}),"completion/complete":tt("completion/complete",Tn),"server/discover":tt("server/discover",{}),"subscriptions/listen":tt("subscriptions/listen",En)};function Xe(xe){return ne({_meta:yr,...xe})}let Vo={"tools/call":Xe({content:O(I),structuredContent:ee().optional(),isError:G().optional()}),"tools/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),tools:O(Yt),nextCursor:n.optional()}),"prompts/get":Xe({description:u().optional(),messages:O(C)}),"prompts/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),prompts:O(P),nextCursor:n.optional()}),"resources/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resources:O(Ce),nextCursor:n.optional()}),"resources/templates/list":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),resourceTemplates:O(ve),nextCursor:n.optional()}),"resources/read":Xe({ttlMs:Z().int().min(0),cacheScope:se(["public","private"]),contents:O(W([fe,Te]))}),"completion/complete":Xe({completion:E({values:O(u()).max(100),total:Z().int().optional(),hasMore:G().optional()}).loose()}),"server/discover":Xe({ttlMs:Z().int().min(0).catch(0),cacheScope:se(["public","private"]).catch("private"),supportedVersions:O(u()),capabilities:hr,instructions:u().optional()}),"subscriptions/listen":Xe({})},tr=ne({"io.modelcontextprotocol/subscriptionId":o.optional()}),zr=E({method:j("notifications/subscriptions/acknowledged"),params:E({_meta:tr.optional(),notifications:$r})}),Rr=E({_meta:tr.optional(),requestId:o,reason:u().optional()}),wr=E({method:j("notifications/cancelled"),params:Rr}),bs={"notifications/cancelled":wr,"notifications/progress":M,"notifications/message":Y,"notifications/resources/updated":V,"notifications/resources/list_changed":k,"notifications/tools/list_changed":oe,"notifications/prompts/list_changed":N,"notifications/subscriptions/acknowledged":zr},Qe=xe=>E({jsonrpc:j("2.0"),id:W([u(),Z().int()]),result:xe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:o,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:s,RelatedTaskMetadataSchema:l,RequestMetaSchema:m,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:z,NotificationsParamsSchema:R,NotificationSchema:v,IconSchema:b,IconsSchema:g,BaseMetadataSchema:d,ImplementationSchema:_,ClientTasksCapabilitySchema:w,ServerTasksCapabilitySchema:y,ClientCapabilitiesSchema:f,ServerCapabilitiesSchema:T,ProgressSchema:A,ProgressNotificationParamsSchema:F,ProgressNotificationSchema:M,LoggingMessageNotificationParamsSchema:D,LoggingMessageNotificationSchema:Y,ResourceContentsSchema:K,TextResourceContentsSchema:fe,BlobResourceContentsSchema:Te,AnnotationsSchema:ze,ResourceSchema:Ce,ResourceTemplateSchema:ve,ResourceListChangedNotificationSchema:k,ResourceUpdatedNotificationParamsSchema:x,ResourceUpdatedNotificationSchema:V,PromptArgumentSchema:$,PromptSchema:P,PromptListChangedNotificationSchema:N,TextContentSchema:H,ImageContentSchema:te,AudioContentSchema:pe,ToolUseContentSchema:ae,EmbeddedResourceSchema:Re,ResourceLinkSchema:Ge,ContentBlockSchema:I,PromptMessageSchema:C,ToolAnnotationsSchema:U,ToolListChangedNotificationSchema:oe,ModelHintSchema:ie,ModelPreferencesSchema:me,ToolChoiceSchema:Ne,BooleanSchemaSchema:qe,StringSchemaSchema:Fe,NumberSchemaSchema:Ae,UntitledSingleSelectEnumSchemaSchema:Ie,TitledSingleSelectEnumSchemaSchema:nt,LegacyTitledEnumSchemaSchema:Ue,SingleSelectEnumSchemaSchema:_t,UntitledMultiSelectEnumSchemaSchema:at,TitledMultiSelectEnumSchemaSchema:St,MultiSelectEnumSchemaSchema:Et,EnumSchemaSchema:It,PrimitiveSchemaDefinitionSchema:Bt,ElicitRequestFormParamsSchema:Kt,ResourceTemplateReferenceSchema:Gt,PromptReferenceSchema:Wt,RootSchema:en,ClientCapabilities2026Schema:tn,ServerCapabilities2026Schema:hr,RequestMetaEnvelopeSchema:gr,ToolSchema:Yt,ToolResultContentSchema:rn,SamplingMessageContentBlockSchema:vr,SamplingMessageSchema:Xt,ResultTypeSchema:_r,ResultMetaSchema:Sr,ResultSchema:nn,PaginatedResultSchema:To,CallToolResultSchema:br,ListToolsResultSchema:on,ListPromptsResultSchema:an,GetPromptResultSchema:sn,ListResourcesResultSchema:cn,ListResourceTemplatesResultSchema:un,ReadResourceResultSchema:ln,CompleteResultSchema:dn,CacheableResultSchema:Eo,DiscoverResultSchema:mn,CreateMessageRequestParamsSchema:kt,CreateMessageRequestSchema:pn,ListRootsRequestSchema:fn,CreateMessageResultSchema:hn,ListRootsResultSchema:gn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:_n,ElicitRequestParamsSchema:Sn,ElicitRequestSchema:yn,InputRequestSchema:bn,InputResponseSchema:$n,InputRequestsSchema:zn,InputResponsesSchema:Rn,InputRequiredResultSchema:Qt,InputResponseRequestParamsSchema:Io,CallToolRequestSchema:ko,ListToolsRequestSchema:Oo,ListPromptsRequestSchema:jo,GetPromptRequestSchema:No,ListResourcesRequestSchema:xo,ListResourceTemplatesRequestSchema:Co,ReadResourceRequestSchema:Ao,CompleteRequestSchema:qo,DiscoverRequestSchema:Mo,SubscriptionFilterSchema:$r,SubscriptionsListenRequestSchema:Uo,SubscriptionsListenResultMetaSchema:Lo,SubscriptionsListenResultSchema:Do,dispatchRequestSchemas:Ot,dispatchResultSchemas:Vo,NotificationMetaSchema:tr,SubscriptionsAcknowledgedNotificationSchema:zr,CancelledNotificationParamsSchema:Rr,CancelledNotificationSchema:wr,notificationSchemas2026:bs,JSONRPCResultResponseSchema:Qe(nn),CallToolResultResponseSchema:Qe(W([br,Qt])),ListToolsResultResponseSchema:Qe(on),ListPromptsResultResponseSchema:Qe(an),GetPromptResultResponseSchema:Qe(W([sn,Qt])),ListResourcesResultResponseSchema:Qe(cn),ListResourceTemplatesResultResponseSchema:Qe(un),ReadResourceResultResponseSchema:Qe(W([ln,Qt])),CompleteResultResponseSchema:Qe(dn),DiscoverResultResponseSchema:Qe(mn)}}var L_;function pr(){return L_??=U_()}var D_=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function V_(e){return D_.includes(e)}var Gr=Symbol("modelcontextprotocol.resultCacheHintFallback");function Wf(e,t){if(t===void 0)return e;let r=e[Gr];if(r===void 0)return{...e,[Gr]:t};let n={},o=r.ttlMs??t.ttlMs;o!==void 0&&(n.ttlMs=o);let i=r.cacheScope??t.cacheScope;return i!==void 0&&(n.cacheScope=i),{...e,[Gr]:n}}function Z_(e){return e[Gr]}function Lu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Du(e){return e==="public"||e==="private"}function Yf(e,t){if(e.ttlMs!==void 0&&!Lu(e.ttlMs))throw new RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!Du(e.cacheScope))throw new RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}var X=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),ge=class Xf extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Wr(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Wr(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",Cu(this,new.target)}static fromError(t,r,n){if(t===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Qf(o.elicitations,r)}if(t===X.UnsupportedProtocolVersion&&n){let o=n;if(Array.isArray(o.supported)&&typeof o.requested=="string")return new Zu({supported:o.supported,requested:o.requested},r)}if(t===X.InvalidParams||t===X.ResourceNotFound){let o=n;if(typeof o?.uri=="string"&&(t===X.ResourceNotFound||Object.keys(o).length===1))return new Vu(o.uri,r)}if(t===X.MissingRequiredClientCapability&&n){let o=n;if(o.requiredCapabilities!==null&&typeof o.requiredCapabilities=="object"&&!Array.isArray(o.requiredCapabilities))return new ts({requiredCapabilities:o.requiredCapabilities},r)}return new Xf(t,r,n)}},Vu=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(X.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Qf=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Zu=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(X.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},ts=class extends ge{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(X.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},F_=0,H_="private",J_=["tools/call","prompts/get","resources/read"];function B_(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||J_.includes(e))return t;throw new ge(X.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function K_(e,t){let r=Z_(t);if(t.resultType!=="complete"||!V_(e))return r===void 0?t:Q_(t);let n=t,o=Lu(n.ttlMs)?n.ttlMs:Y_(r),i=Du(n.cacheScope)?n.cacheScope:X_(r),a={...n,ttlMs:o,cacheScope:i};return delete a[Gr],a}function G_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W_(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Rt]:t}}:!G_(r)||r[Rt]!==void 0?e:{...e,_meta:{...r,[Rt]:t}}}function Y_(e){return e!==void 0&&Lu(e.ttlMs)?e.ttlMs:F_}function X_(e){return e!==void 0&&Du(e.cacheScope)?e.cacheScope:H_}function Q_(e){let t={...e};return delete t[Gr],t}var eS=["elicitation/create","sampling/createMessage","roots/list"],Ga;function eh(){if(Ga)return Ga;let e=pr();return Ga={request:{"elicitation/create":E({method:j("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":E({method:j("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":E({method:j("roots/list"),params:ne({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Ga}function th(e){return eS.includes(e)}function Tu(e){return th(e)?eh().request[e]:void 0}function tS(e){return th(e)?eh().response[e]:void 0}var Fu={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},rh={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function nh(e){return Object.prototype.hasOwnProperty.call(Fu,e)}function oh(e){return Object.prototype.hasOwnProperty.call(rh,e)}function rS(e){return Object.prototype.hasOwnProperty.call(Fu,e)}function nS(e){return nh(e)?pr().dispatchRequestSchemas[e]:void 0}function oS(e){return rS(e)?pr().dispatchResultSchemas[e]:void 0}function iS(e){return oh(e)?pr().notificationSchemas2026[e]:void 0}var iT=Object.keys(Fu),aT=Object.keys(rh);function So(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var aS={ok:!1,reason:"not-in-era"},sS=[ur,wt];function cS(e,t){let r=t,n=!1,o=()=>(n||(r={...r},n=!0),r),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>So(c)&&"execution"in c)&&(o().tools=i.map(c=>{if(!So(c)||!("execution"in c))return c;let s={...c};return delete s.execution,s}));let a=t.capabilities;if(So(a)&&"tasks"in a){let c={...a};delete c.tasks,o().capabilities=c}return r}var Hu={era:"2026-07-28",hasRequestMethod:nh,hasNotificationMethod:oh,hasInputRequestMethod:e=>Tu(e)!==void 0,validateRequest:(e,t)=>vo(nS(e),t),validateResult:(e,t)=>vo(oS(e),t),validateNotification:(e,t)=>vo(iS(e),t),validateInputRequest:(e,t)=>vo(Tu(e),t),validateInputResponse:(e,t)=>vo(tS(e),t),samplingResultVariant:()=>aS,outboundEnvelope(e){return{[ur]:e.protocolVersion,[qr]:e.clientInfo,[wt]:e.clientCapabilities,...e.logLevel!==void 0&&{[Ut]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of sS)n in e||t.push({key:n,problem:"missing"});let r=pr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let o=n.path.map(String),i=o.length>0?o.join("."):"_meta";o.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:e=>Vf(e),inputRequestSchema:Tu,decodeResult(e,t){if(!So(t))return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=So(a)?a:{},s=t.requestState;return Object.keys(c).length===0&&typeof s!="string"?{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof s=="string"&&{requestState:s}}}if(r!=="complete")return{kind:"invalid",error:new le(he.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=uS(),o=Object.hasOwn(n,e)?n[e]:void 0;if(o!==void 0){let a=o.safeParse(t);if(!a.success)return{kind:"invalid",error:new le(he.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return W_(K_(e,B_(e,cS(e,t))),r)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=pr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Wa;function uS(){if(Wa)return Wa;let e=pr();return Wa={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Wa}var Ju="2026-07-28";function Yr(e){return e!==void 0&&$o(e)?Hu:Uu}function Of(e){return e.revision!==void 0?Yr(e.revision).era:e.era==="modern"?Hu.era:Uu.era}function Eu(e){return ih.some(t=>t.hasRequestMethod(e))}function Iu(e){return ih.some(t=>t.hasNotificationMethod(e))}var ih=[Uu,Hu];var lS=Rl({AnnotationsSchema:()=>Tt,AudioContentSchema:()=>Fr,BaseMetadataSchema:()=>zt,BaseRequestParamsSchema:()=>De,BlobResourceContentsSchema:()=>oo,BooleanSchemaSchema:()=>uo,CallToolRequestParamsSchema:()=>aa,CallToolRequestSchema:()=>sa,CallToolResultSchema:()=>co,CancelTaskRequestSchema:()=>lu,CancelTaskResultSchema:()=>du,CancelledNotificationParamsSchema:()=>ui,CancelledNotificationSchema:()=>Xn,ClientCapabilitiesSchema:()=>pi,ClientNotificationSchema:()=>pu,ClientRequestSchema:()=>mu,ClientResultSchema:()=>fu,ClientTasksCapabilitySchema:()=>di,CompatibilityCallToolResultSchema:()=>Qc,CompleteRequestParamsSchema:()=>xa,CompleteRequestSchema:()=>Ca,CompleteResultSchema:()=>Aa,ContentBlockSchema:()=>Hr,CreateMessageRequestParamsSchema:()=>Sa,CreateMessageRequestSchema:()=>ya,CreateMessageResultSchema:()=>ba,CreateMessageResultWithToolsSchema:()=>$a,CreateTaskResultSchema:()=>ru,CursorSchema:()=>Hn,DiscoverRequestSchema:()=>_i,DiscoverResultSchema:()=>Si,ElicitRequestFormParamsSchema:()=>Kr,ElicitRequestParamsSchema:()=>Ea,ElicitRequestSchema:()=>Ia,ElicitRequestURLParamsSchema:()=>Ta,ElicitResultSchema:()=>Oa,ElicitationCompleteNotificationParamsSchema:()=>Pa,ElicitationCompleteNotificationSchema:()=>ka,EmbeddedResourceSchema:()=>Yi,EmptyResultSchema:()=>Yn,EnumSchemaSchema:()=>wa,GetPromptRequestParamsSchema:()=>Ki,GetPromptRequestSchema:()=>Gi,GetPromptResultSchema:()=>ea,GetTaskPayloadRequestSchema:()=>au,GetTaskPayloadResultSchema:()=>su,GetTaskRequestSchema:()=>ou,GetTaskResultSchema:()=>iu,IconSchema:()=>li,IconsSchema:()=>Dt,ImageContentSchema:()=>Zr,ImplementationSchema:()=>Lr,InitializeRequestParamsSchema:()=>fi,InitializeRequestSchema:()=>hi,InitializeResultSchema:()=>gi,InitializedNotificationSchema:()=>vi,JSONArraySchema:()=>Wc,JSONObjectSchema:()=>ke,JSONRPCErrorResponseSchema:()=>Ur,JSONRPCMessageSchema:()=>Wn,JSONRPCNotificationSchema:()=>Gn,JSONRPCRequestSchema:()=>Kn,JSONRPCResponseSchema:()=>Yc,JSONRPCResultResponseSchema:()=>Mr,JSONValueSchema:()=>Mt,LegacyTitledEnumSchemaSchema:()=>po,ListChangedOptionsBaseSchema:()=>eu,ListPromptsRequestSchema:()=>Ji,ListPromptsResultSchema:()=>Bi,ListResourceTemplatesRequestSchema:()=>Ti,ListResourceTemplatesResultSchema:()=>Ei,ListResourcesRequestSchema:()=>Ri,ListResourcesResultSchema:()=>wi,ListRootsRequestSchema:()=>Ma,ListRootsResultSchema:()=>Ua,ListTasksRequestSchema:()=>cu,ListTasksResultSchema:()=>uu,ListToolsRequestSchema:()=>oa,ListToolsResultSchema:()=>ia,LoggingLevelSchema:()=>Ht,LoggingMessageNotificationParamsSchema:()=>da,LoggingMessageNotificationSchema:()=>ma,ModelHintSchema:()=>pa,ModelPreferencesSchema:()=>fa,MultiSelectEnumSchemaSchema:()=>Ra,NotificationSchema:()=>Ke,NotificationsParamsSchema:()=>Be,NumberSchemaSchema:()=>Br,PaginatedRequestParamsSchema:()=>$i,PaginatedRequestSchema:()=>Vt,PaginatedResultSchema:()=>Zt,PingRequestSchema:()=>eo,PrimitiveSchemaDefinitionSchema:()=>go,ProgressNotificationParamsSchema:()=>bi,ProgressNotificationSchema:()=>to,ProgressSchema:()=>yi,ProgressTokenSchema:()=>Fn,PromptArgumentSchema:()=>Fi,PromptListChangedNotificationSchema:()=>ta,PromptMessageSchema:()=>Qi,PromptReferenceSchema:()=>Na,PromptSchema:()=>Hi,ReadResourceRequestParamsSchema:()=>Ii,ReadResourceRequestSchema:()=>Pi,ReadResourceResultSchema:()=>ki,RelatedTaskMetadataSchema:()=>ci,RequestIdSchema:()=>Lt,RequestMetaSchema:()=>Jn,RequestSchema:()=>Oe,ResourceContentsSchema:()=>ro,ResourceLinkSchema:()=>Xi,ResourceListChangedNotificationSchema:()=>Oi,ResourceRequestParamsSchema:()=>Dr,ResourceSchema:()=>io,ResourceTemplateReferenceSchema:()=>ja,ResourceTemplateSchema:()=>zi,ResourceUpdatedNotificationParamsSchema:()=>Vi,ResourceUpdatedNotificationSchema:()=>Zi,ResultMetaObjectSchema:()=>Bn,ResultSchema:()=>je,RoleSchema:()=>Ft,RootSchema:()=>qa,RootsListChangedNotificationSchema:()=>La,SamplingContentSchema:()=>va,SamplingMessageContentBlockSchema:()=>sr,SamplingMessageSchema:()=>_a,ServerCapabilitiesSchema:()=>Qn,ServerNotificationSchema:()=>gu,ServerRequestSchema:()=>hu,ServerResultSchema:()=>vu,ServerTasksCapabilitySchema:()=>mi,SetLevelRequestParamsSchema:()=>ua,SetLevelRequestSchema:()=>la,SingleSelectEnumSchemaSchema:()=>za,StringSchemaSchema:()=>Jr,SubscribeRequestParamsSchema:()=>ji,SubscribeRequestSchema:()=>Ni,SubscriptionFilterSchema:()=>ao,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Mi,SubscriptionsAcknowledgedNotificationSchema:()=>Ui,SubscriptionsListenRequestParamsSchema:()=>Ai,SubscriptionsListenRequestSchema:()=>qi,SubscriptionsListenResultMetaSchema:()=>Li,SubscriptionsListenResultSchema:()=>Di,TaskAugmentedRequestParamsSchema:()=>dr,TaskCreationParamsSchema:()=>tu,TaskMetadataSchema:()=>si,TaskSchema:()=>Jt,TaskStatusNotificationParamsSchema:()=>Va,TaskStatusNotificationSchema:()=>nu,TaskStatusSchema:()=>Da,TextContentSchema:()=>Vr,TextResourceContentsSchema:()=>no,TitledMultiSelectEnumSchemaSchema:()=>ho,TitledSingleSelectEnumSchemaSchema:()=>mo,ToolAnnotationsSchema:()=>ra,ToolChoiceSchema:()=>ha,ToolExecutionSchema:()=>na,ToolListChangedNotificationSchema:()=>ca,ToolResultContentSchema:()=>ga,ToolSchema:()=>so,ToolUseContentSchema:()=>Wi,UnsubscribeRequestParamsSchema:()=>xi,UnsubscribeRequestSchema:()=>Ci,UntitledMultiSelectEnumSchemaSchema:()=>fo,UntitledSingleSelectEnumSchemaSchema:()=>lo});var Bu=e=>Kn.safeParse(e).success,Ku=e=>Gn.safeParse(e).success,Qa=e=>Mr.safeParse(e).success,Gu=e=>Ur.safeParse(e).success;var fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var Ya=-32020,sT=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[X.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Ya,X.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[X.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[X.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[X.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Ya],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[X.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Ya],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],dS={[X.ParseError]:400,[X.InvalidRequest]:400,[X.MethodNotFound]:404,[X.UnsupportedProtocolVersion]:400,[X.MissingRequiredClientCapability]:400,[Ya]:400};function rs(e,t){return ti(e,t)}function _o(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function ju(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}var jf=!1,Nu="draft-2020-12";function ah(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Nu});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");jf||(jf=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=Dn(e,{target:Nu,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:sh(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}function sh(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||sh(n)))}return!1}function mS(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Xa(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>mS(n)).join(", ")}:{success:!0,data:r.value}}function pS(e){let t=Dn(e,{target:Nu,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}var fS=/\\\.\\d\{(\d+)\}/;function hS(e){let t=fS.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(o=>r.map(i=>lt.datetime({local:n,offset:o,precision:i}))))}function gS(e,t){let r;switch(e){case"email":r=[Hc()];break;case"uri":r=[Vn()];break;case"date":r=[lt.date()];break;case"date-time":r=hS(t);break}return new Set(r.map(n=>pS(n)).filter(n=>n!==void 0))}function vS(e,t,r){return r!=="zod"?!0:gS(e,t).has(t)}function bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _S(e){try{return ah(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ge(X.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var SS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Wu(e){return SS.has(e)||e.startsWith("x-")}var yS=new Set(["$schema",...Object.keys(Kr.shape.requestedSchema.shape)]),Nf={string:_o([Jr,lo,mo,po]),number:_o([Br]),integer:_o([Br]),boolean:_o([uo]),array:_o([fo,ho])},bS=new Set(Jr.shape.format.unwrap().options);function $S(e,t,r,n){if(!bo(e))return e;let o=typeof e.type=="string"&&Object.hasOwn(Nf,e.type)?Nf[e.type]:void 0;if(o===void 0)return e;let i={};for(let[a,c]of Object.entries(e))o.has(a)||Wu(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?bS.has(e.format)?(typeof c!="string"||!vS(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}function zS(e,t){let r={},n=[];for(let[o,i]of Object.entries(e))o==="properties"&&bo(i)?r[o]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,$S(c,`properties.${a}`,t,n)])):yS.has(o)?r[o]=i:Wu(o)||n.push(o);if(n.length>0)throw new ge(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}function RS(e,t){if(!bo(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!rs(go,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}function xu(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,o)=>xu(n,t[o],`${r}[${o}]`)):!bo(e)||!bo(t)?[]:Object.entries(e).flatMap(([n,o])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?xu(o,t[n],i):Wu(n)?[]:[i]})}function wS(e){if(!ju(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=zS(_S(e.requestedSchema),t),n=rs(Kr.shape.requestedSchema,r);if(!n.success)throw new ge(X.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${RS(r,n.error.message)}`);let o=xu(r,n.data);if(o.length>0)throw new ge(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new ge(X.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}function TS(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var ES=Object.assign(TS,{elicit(e){try{return{method:"elicitation/create",params:wS(e)}}catch(t){throw t instanceof ge?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var ch=250;function uh(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function lh(e,t){return new Promise((r,n)=>{if(t?.aborted){n(t.reason instanceof le?t.reason:new le(he.RequestTimeout,String(t.reason)));return}let o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(o),n(t?.reason instanceof le?t.reason:new le(he.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function dh(e){let t=new AbortController,r=()=>t.abort(e?.reason);return e?.addEventListener("abort",r,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:n=>t.abort(n),dispose:()=>e?.removeEventListener("abort",r)}}var IS=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],PS={IdJagTokenExchangeResponseSchema:bu,OAuthClientInformationFullSchema:zu,OAuthClientInformationSchema:Ja,OAuthClientMetadataSchema:Ha,OAuthClientRegistrationErrorSchema:Ru,OAuthErrorResponseSchema:$u,OAuthMetadataSchema:Za,OAuthProtectedResourceMetadataSchema:_u,OAuthTokenRevocationRequestSchema:wu,OAuthTokensSchema:yu,OpenIdProviderDiscoveryMetadataSchema:Su,OpenIdProviderMetadataSchema:Fa},mh={},ph={};function fh(e,t){let r=e.slice(0,-6);mh[r]=t,ph[r]=n=>t.safeParse(n).success}for(let e of IS)fh(e,lS[e]);for(let[e,t]of Object.entries(PS))fh(e,t);var kS=Object.freeze(mh),OS=Object.freeze(ph);function jS(e){switch(e){case"initialize":case"notifications/initialized":return Yr(void 0);case"server/discover":return Yr(Ju);default:return}}var hh=6e4,NS=[ur,qr,wt,Ut],xS=["inputResponses","requestState"];function xf(e,t){let r=e.params;if(!yo(r))return{message:e,lifted:{}};let n=r._meta,o=yo(n)?NS.filter(s=>s in n):[],i=t==="request"?xS.filter(s=>s in r):[];if(o.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(o.length>0&&yo(n)){let s={},l={...n};for(let m of o)s[m]=n[m],delete l[m];a.envelope=s,Object.keys(l).length>0?c._meta=l:delete c._meta}for(let s of i)s==="inputResponses"&&(a.inputResponses=c[s]),s==="requestState"&&(a.requestState=c[s]),delete c[s];return{message:{...e,params:c},lifted:a}}function Cf(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let o=e.validateResult(t,n);return o.ok?{value:o.value}:{issues:[{message:o.reason==="invalid"?o.message:`not-in-era: ${t}`}]}}}}}function zo(e){return()=>e}var CS=zo(void 0);function Yu(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:zo(t)}}}var AS;var Xu=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{AS=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ii,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new le(he.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new le(he.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),Qa(o)||Gu(o)?this._onresponse(o):Bu(o)?this._onrequest(o,i):Ku(o)?this._onnotification(o,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new le(he.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=xf(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Of(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(Iu(r.method)&&!n.hasNotificationMethod(r.method))return;let o=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;o===void 0&&i===void 0||Promise.resolve().then(()=>o===void 0?i(r):o(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=xf(e,"request"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=(b,g,d)=>{let _={jsonrpc:"2.0",id:r.id,error:{code:b,message:g,...d!==void 0&&{data:d}}};i?.send(_).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)))};if(t?.classification!==void 0){let b=Of(t.classification);if(b!==o.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${b} but this instance serves ${o.era}`));let g=t.classification.revision??b;a(X.UnsupportedProtocolVersion,`Unsupported protocol version: ${g}`,{supported:this._supportedProtocolVersions,requested:g});return}}if(Eu(r.method)&&!o.hasRequestMethod(r.method)){a(X.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(X.MethodNotFound,"Method not found");return}let s=o.checkInboundEnvelope(n);if(s!==void 0){a(X.InvalidParams,s);return}let l=(b,g)=>this._notificationViaCodec(this._resolveOutboundCodec(b.method),b,{...g,relatedRequestId:r.id}),m=(b,g,d)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(b.method),b,g,{...d,relatedRequestId:r.id}),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let z=n.inputResponses===void 0?void 0:qS(n.inputResponses),R={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...z!==void 0&&{inputResponses:z.accepted},...z!==void 0&&z.droppedKeys.length>0&&{droppedInputResponseKeys:z.droppedKeys},requestState:n.requestState===void 0?CS:zo(n.requestState),signal:h.signal,send:((b,g,d)=>{let _=this._resolveOutboundCodec(b.method);if(this._assertOutboundRequestInEra(_,b.method),ju(g))return m(b,g,d);let p=Cf(_,b.method);if(p===void 0)throw new TypeError(`'${b.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(b,p,g)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},v=this.buildContext(R,t);Promise.resolve().then(()=>c(r,v)).then(async b=>{if(h.signal.aborted)return;let g;try{g=o.encodeResult(r.method,b,this._outboundServerInfo())}catch(_){this._onerror(new Error(`Failed to encode result for ${r.method}: ${_}`)),a(X.InternalError,"Internal error");return}let d={result:g,jsonrpc:"2.0",id:r.id};await i?.send(d)},async b=>{if(h.signal.aborted)return;let g=Number.isSafeInteger(b.code)?b.code:X.InternalError,d={jsonrpc:"2.0",id:r.id,error:{code:o.encodeErrorCode(g),message:b.message??"Internal error",...b.data!==void 0&&{data:b.data}}};await i?.send(d)}).catch(b=>this._onerror(new Error(`Failed to send response: ${b}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Qa(e)?r(e):r(ge.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(n,e.method),ju(t))return this._requestWithSchemaViaCodec(n,e,t,r);let o=Cf(n,e.method);if(o===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,o,t)}_negotiatedWireCodec(){return Yr(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=jS(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Eu(t)&&!e.hasRequestMethod(t))throw new le(he.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:c}=n??{},s=Date.now(),l,m;return new Promise((h,z)=>{let R=y=>{z(y)};if(!this._transport){R(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(y){R(y);return}if(n?.signal?.aborted){let y=n.signal.reason;throw y instanceof le?y:new le(he.RequestTimeout,String(y))}let v=e.era===Ju&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,b=this._requestMessageId++;m=b;let g={...t,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:b}});let d=this._envelopeOutbound(g),_=!1,p=y=>{_||(this._progressHandlers.delete(b),v===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(y)}}),{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(f=>this._onerror(new Error(`Failed to send cancellation: ${f}`))):v.abort(),z(y instanceof le?y:new le(he.RequestTimeout,String(y))))};this._responseHandlers.set(b,y=>{if(n?.signal?.aborted)return;if(_=!0,y instanceof Error)return z(y);let f;try{f=e.decodeResult(t.method,y.result)}catch(A){return z(A instanceof Error?A:new Error(String(A)))}if(f.kind==="invalid")return z(f.error);if(f.kind==="input_required"){if(n?.allowInputRequired===!0)return h(MS(f));let A={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:s,retry:(F,M)=>this._requestWithSchemaViaCodec(e,F===void 0?{method:t.method}:{method:t.method,params:F},r,M)};return h(this._resolveNonCompleteResult(f,A))}let T=f.result;Xa(r,T).then(A=>{A.success?h(A.data):z(new le(he.InvalidResult,`Invalid result for ${t.method}: ${A.error}`))},z)}),l=()=>p(n?.signal?.reason),n?.signal?.addEventListener("abort",l,{once:!0});let S=n?.timeout??hh,w=()=>p(new le(he.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(b,S,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1),this._transport.send(d,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:v?.signal}).catch(y=>{this._progressHandlers.delete(b),z(y)})}).finally(()=>{l&&n?.signal?.removeEventListener("abort",l),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new le(he.NotConnected,"Not connected");if(Iu(t.method)&&!e.hasNotificationMethod(t.method))throw new le(he.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(o=>this._onerror(o))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Eu(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(o,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,o);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,o)),!c.ok)throw c.reason==="not-in-era"?new ge(X.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))}}else if(r)n=async(o,i)=>{let a=await Xa(t.params,{...o.params});if(!a.success)throw new ge(X.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)};else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}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,r){if(typeof t=="function"){if(!Iu(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,o)=>{let i=o.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new ge(X.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let o=await Xa(t.params,{...n.params});if(!o.success)throw new ge(X.InvalidParams,`Invalid params for notification ${e}: ${o.error}`);await r(o.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function yo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qu(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let a=r[o];r[o]=yo(a)&&yo(i)?{...a,...i}:i}return r}function Af(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qS(e){let t={},r=[];if(!Af(e))return{accepted:t,droppedKeys:r};for(let[n,o]of Object.entries(e)){if(!Af(o)||"method"in o||"result"in o){r.push(n);continue}t[n]=o}return{accepted:t,droppedKeys:r}}function MS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}var US=L((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=o;function o(c){if(!c)throw new TypeError("argument string is required");var s=typeof c=="object"?i(c):c;if(typeof s!="string")throw new TypeError("argument string is required to be a string");var l=s.indexOf(";"),m=l!==-1?s.slice(0,l).trim():s.trim();if(!n.test(m))throw new TypeError("invalid media type");var h=new a(m.toLowerCase());if(l!==-1){var z,R,v;for(t.lastIndex=l;R=t.exec(s);){if(R.index!==l)throw new TypeError("invalid parameter format");l+=R[0].length,z=R[1].toLowerCase(),v=R[2],v.charCodeAt(0)===34&&(v=v.slice(1,-1),v.indexOf("\\")!==-1&&(v=v.replace(r,"$1"))),h.parameters[z]=v}if(l!==s.length)throw new TypeError("invalid parameter format")}return h}function i(c){var s;if(typeof c.getHeader=="function"?s=c.getHeader("content-type"):typeof c.headers=="object"&&(s=c.headers&&c.headers["content-type"]),typeof s!="string")throw new TypeError("content-type header is missing from object");return s}function a(c){this.parameters=Object.create(null),this.type=c}})),cT=Fo(US(),1);var gh=10*1024*1024,el=class{_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??gh}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(` diff --git a/tests/mcp-v2-migration-contract.test.ts b/tests/mcp-v2-migration-contract.test.ts index afcd447c..d328f8c8 100644 --- a/tests/mcp-v2-migration-contract.test.ts +++ b/tests/mcp-v2-migration-contract.test.ts @@ -12,6 +12,7 @@ describe("MCP TypeScript SDK v2 migration contract", () => { const dependencies = manifest.dependencies ?? {}; expect(dependencies).not.toHaveProperty("@modelcontextprotocol/sdk"); + expect(dependencies).not.toHaveProperty("@modelcontextprotocol/server-legacy"); expect(dependencies).toMatchObject({ "@modelcontextprotocol/client": "^2.0.0", "@modelcontextprotocol/core": "^2.0.0", diff --git a/tests/mcp-v2-serving.test.ts b/tests/mcp-v2-serving.test.ts index e68b8c5c..51e92de8 100644 --- a/tests/mcp-v2-serving.test.ts +++ b/tests/mcp-v2-serving.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { access, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; @@ -22,7 +22,10 @@ afterEach(async () => { await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))); }); -async function configPath(upstream?: { readonly url: string }): Promise { +async function configPath(upstream?: { + readonly url?: string; + readonly env?: Readonly>; +}): Promise { const directory = await mkdtemp(join(tmpdir(), "miftah-v2-serving-")); temporaryDirectories.push(directory); const path = join(directory, "miftah.json"); @@ -32,8 +35,13 @@ async function configPath(upstream?: { readonly url: string }): Promise version: "1", name: "v2-serving-test", defaultProfile: "work", - upstream: upstream === undefined - ? { transport: "stdio", command: process.execPath, args: [fixture] } + upstream: upstream?.url === undefined + ? { + transport: "stdio", + command: process.execPath, + args: [fixture], + ...(upstream?.env === undefined ? {} : { env: upstream.env }) + } : { transport: "streamable-http", url: upstream.url }, profiles: { work: {} }, server: { http: { port: 0, maxSessions: 4, sessionIdleTimeoutMs: 1_000 } } @@ -71,6 +79,34 @@ describe("MCP SDK v2 serving interoperability", () => { } }); + it("does not probe or advertise connection-bound resource subscriptions for modern HTTP requests", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-v2-serving-probe-")); + temporaryDirectories.push(directory); + const startCountPath = join(directory, "upstream-start-count"); + const server = await startMiftahHttpServer(await configPath({ + env: { + TEST_RESOURCE_SUBSCRIPTIONS: "true", + TEST_START_COUNT_PATH: startCountPath + } + })); + httpServers.push(server); + const transport = new StreamableHTTPClientTransport(server.url); + const client = new Client( + { name: "miftah-modern-http-subscription-test", version: "1.0.0" }, + { versionNegotiation: { mode: "auto" } } + ); + + try { + await client.connect(transport); + expect(client.getServerCapabilities()?.resources?.subscribe).not.toBe(true); + await expect(access(startCountPath)).rejects.toMatchObject({ code: "ENOENT" }); + expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); + await expect.poll(async () => access(startCountPath).then(() => true, () => false)).toBe(true); + } finally { + await client.close(); + } + }); + it("preserves the legacy initialized Streamable HTTP session path", async () => { const server = await startMiftahHttpServer(await configPath()); httpServers.push(server); diff --git a/tests/remote-oauth-client-provider.test.ts b/tests/remote-oauth-client-provider.test.ts index 82531065..5d9a03f8 100644 --- a/tests/remote-oauth-client-provider.test.ts +++ b/tests/remote-oauth-client-provider.test.ts @@ -258,7 +258,8 @@ describe("remote OAuth client provider", () => { await expect(restarted.tokens()).resolves.toMatchObject({ access_token: "fixture-access-token" }); await expect(restarted.clientInformation()).resolves.toMatchObject({ client_id: "fixture-dynamic-client", - client_secret: "fixture-dynamic-client-secret" + client_secret: "fixture-dynamic-client-secret", + issuer: "https://issuer.example.test" }); }); diff --git a/tests/test-harness-resource-contract.test.ts b/tests/test-harness-resource-contract.test.ts index 8ad36fe5..d21f1b00 100644 --- a/tests/test-harness-resource-contract.test.ts +++ b/tests/test-harness-resource-contract.test.ts @@ -1,8 +1,14 @@ import { spawnSync } from "node:child_process"; -import { readFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { join } from "node:path"; +import { pathToFileURL } from "node:url"; import { describe, expect, it } from "vitest"; +interface TestFixtureBuilder { + buildTestFixtureSource(entryPoint?: string): Promise; +} + describe("test harness resource contract", () => { it("does not copy the Node runtime merely to create executable path markers", async () => { for (const relativePath of ["tests/executable-resolver.test.ts", "tests/secret-providers.test.ts"]) { @@ -30,4 +36,23 @@ describe("test harness resource contract", () => { expect(bundleCheck.error).toBeUndefined(); expect(bundleCheck.status, bundleCheck.stderr).toBe(0); }); + + it("preserves indented blank lines inside bundled template literals", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-fixture-template-")); + try { + const entryPath = join(directory, "entry.mjs"); + const outputPath = join(directory, "output.mjs"); + const expected = "first\n \nlast"; + await writeFile(entryPath, ["export const fixture = `first", " ", "last`;", ""].join("\n")); + // @ts-expect-error The production fixture builder is intentionally plain Node ESM. + const builder = await import("../scripts/build-test-fixture.mjs") as TestFixtureBuilder; + const output = await builder.buildTestFixtureSource(entryPath); + expect(output).not.toMatch(/^[\t ]+$/mu); + await writeFile(outputPath, output); + const bundled = await import(`${pathToFileURL(outputPath).href}?test=${Date.now()}`) as { fixture: string }; + expect(bundled.fixture).toBe(expected); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); }); From 4c203444d26026d8e489255d19e775a35e17eb5d Mon Sep 17 00:00:00 2001 From: mohammed naji Date: Tue, 11 Aug 2026 19:05:38 +0400 Subject: [PATCH 4/4] fix: complete MCP v2 approval compatibility --- CHANGELOG.md | 2 +- docs/library-api.md | 2 + scripts/build-test-fixture.mjs | 16 +- src/approvals/approval-continuation-store.ts | 147 ++++++++++++++++ src/mcp/server/miftah-server.ts | 174 ++++++++++++------- src/mcp/server/operation-pipeline.ts | 5 +- src/runtime/create-miftah-runtime.ts | 17 +- tests/approval-continuation-store.test.ts | 95 ++++++++++ tests/mcp-v2-serving.test.ts | 74 +++++++- tests/mcp-wrapper.test.ts | 26 +++ 10 files changed, 483 insertions(+), 75 deletions(-) create mode 100644 src/approvals/approval-continuation-store.ts create mode 100644 tests/approval-continuation-store.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 040ec782..0e45f7a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ All notable changes to this project will be documented in this file. The format ### Changed -- [#363](https://github.com/mohanagy/miftah/issues/363) Replaced the monolithic MCP TypeScript SDK v1 dependency with the stable v2 split packages and migrated runtime schemas to Zod 4. Runtime consumers receive only `client`, `core`, and `server`; the Node adapter and frozen legacy server remain build/test dependencies. Direct consumers of the old monolithic SDK deep imports must move to the corresponding split package. The CLI bundles the v2 Node adapter with patched `@hono/node-server` and Hono builds so a fresh Miftah install does not inherit the Node package's still-vulnerable 1.x adapter range; custom embedding hosts own their direct Node adapter version. Native OAuth callback completion now carries the authorization-server issuer required by the v2 provider contract; Miftah continues to validate and round-trip that issuer without exposing tokens or client secrets. +- [#363](https://github.com/mohanagy/miftah/issues/363) Replaced the monolithic MCP TypeScript SDK v1 dependency with the stable v2 split packages and migrated runtime schemas to Zod 4. Runtime consumers receive only `client`, `core`, and `server`; the Node adapter and frozen legacy server remain build/test dependencies. Direct consumers of the old monolithic SDK deep imports must move to the corresponding split package. The CLI bundles the v2 Node adapter with patched `@hono/node-server` and Hono builds so a fresh Miftah install does not inherit the Node package's still-vulnerable 1.x adapter range; custom embedding hosts own their direct Node adapter version. Confirmation-required tools, resources, prompts, and profile transitions now use the v2 `input_required` flow with integrity-bound one-time continuation state across request-scoped modern HTTP instances, while the SDK legacy shim preserves form elicitation for initialized clients. Native OAuth callback completion now carries the authorization-server issuer required by the v2 provider contract; Miftah continues to validate and round-trip that issuer without exposing tokens or client secrets. ## [1.0.0] - 2026-08-11 diff --git a/docs/library-api.md b/docs/library-api.md index c4848514..81a840e6 100644 --- a/docs/library-api.md +++ b/docs/library-api.md @@ -50,6 +50,8 @@ For a custom HTTP host, pass the same factory to `createMcpHandler` from `@model This matrix describes Miftah's tested serving boundary, not a promise that every optional feature added to any future MCP revision is implemented. The SDK v2 serving entry owns protocol-era negotiation; Miftah continues to own broker routing, policy, audit, OAuth, profile state, upstream lifecycle, and cancellation propagation. +Confirmation-required tools, resource reads, prompt reads, and profile transitions return the MCP `input_required` result on the modern era. Miftah binds the continuation to the exact operation with bounded, integrity-protected, one-time state shared by the server factory, so a fresh request-scoped HTTP instance can safely finish the approval without retaining raw operation arguments. The SDK's legacy shim translates the same handler flow into form elicitation for initialized clients. + ## Authenticated request context The additive authenticated request-context API is the trust seam for future modern stateless handling. An embedding host supplies a verifier callback that returns `VerifiedHttpRequestClaims` only after it has authenticated the request. Miftah does not parse MCP `clientInfo`, arbitrary headers, request metadata, tool arguments, or a model-generated conversation ID into this boundary. diff --git a/scripts/build-test-fixture.mjs b/scripts/build-test-fixture.mjs index 34d4117f..f0bc070a 100644 --- a/scripts/build-test-fixture.mjs +++ b/scripts/build-test-fixture.mjs @@ -29,7 +29,8 @@ export function normalizeTemplateLiteralWhitespace(source) { ts.isTemplateTail(node) ) { const value = source.slice(node.getStart(sourceFile), node.getEnd()); - if (/^[\t ]+$/mu.test(value)) { + const whitespaceOnlyLines = [...value.matchAll(/^[\t ]+$/gmu)]; + if (whitespaceOnlyLines.length > 0) { const template = ts.isNoSubstitutionTemplateLiteral(node) ? node : ts.isTemplateExpression(node.parent) @@ -38,11 +39,14 @@ export function normalizeTemplateLiteralWhitespace(source) { if (ts.isTaggedTemplateExpression(template.parent)) { throw new Error("Cannot safely normalize whitespace inside a tagged template literal."); } - replacements.push({ - start: node.getStart(sourceFile), - end: node.getEnd(), - value: value.replace(/^[\t ]+$/gmu, escapedWhitespace) - }); + for (const match of whitespaceOnlyLines) { + if (match.index === undefined) continue; + replacements.push({ + start: node.getStart(sourceFile) + match.index, + end: node.getStart(sourceFile) + match.index + match[0].length, + value: escapedWhitespace(match[0]) + }); + } } } ts.forEachChild(node, visit); diff --git a/src/approvals/approval-continuation-store.ts b/src/approvals/approval-continuation-store.ts new file mode 100644 index 00000000..9a1c4ad0 --- /dev/null +++ b/src/approvals/approval-continuation-store.ts @@ -0,0 +1,147 @@ +import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import type { InputRequiredResult } from "@modelcontextprotocol/server"; +import type { ApprovalBinding, ApprovalSummary } from "./approval-store.js"; +import { MiftahError } from "../utils/errors.js"; + +const DEFAULT_MAX_RECORDS = 128; +const MAX_STATE_LENGTH = 512; + +export interface ApprovalContinuation { + readonly approvalId: string; +} + +/** Internal control flow that carries an MCP multi-round-trip result through policy and audit layers. */ +export class ApprovalInputRequiredSignal extends Error { + constructor( + readonly result: InputRequiredResult, + readonly errorCode: MiftahError["code"] + ) { + super("MCP input is required before the operation can continue."); + this.name = "ApprovalInputRequiredSignal"; + } +} + +interface ApprovalContinuationRecord { + readonly bindingDigest: Buffer; + readonly approval: ApprovalSummary; +} + +function canonicalJson(value: unknown): string { + if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null"; + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; + const entries = Object.entries(value as Record) + .filter(([, entry]) => entry !== undefined) + .sort(([left], [right]) => left.localeCompare(right)); + return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; +} + +function invalidContinuation(): MiftahError { + return new MiftahError("APPROVAL_INVALID", "APPROVAL_INVALID: approval continuation is invalid or no longer pending"); +} + +/** Keeps form-approval retries bounded, integrity-protected, and usable across request-scoped server instances. */ +export class ApprovalContinuationStore { + private readonly records = new Map(); + private readonly stateKey = randomBytes(32); + private readonly bindingKey = randomBytes(32); + + constructor(private readonly maxRecords = DEFAULT_MAX_RECORDS) { + if (!Number.isInteger(maxRecords) || maxRecords <= 0) { + throw new Error("Approval continuation record limit must be a positive integer."); + } + } + + mint(binding: ApprovalBinding, approval: ApprovalSummary): string { + this.discardExpired(); + if (this.records.size >= this.maxRecords) { + throw new MiftahError("APPROVAL_LIMIT_EXCEEDED", "APPROVAL_LIMIT_EXCEEDED: too many outstanding approvals"); + } + this.records.set(approval.id, { + bindingDigest: this.digestBinding(binding), + approval + }); + return this.state({ approvalId: approval.id }); + } + + /** Verifies wire integrity before the SDK exposes decoded state to a request handler. */ + verify(state: string): ApprovalContinuation { + if (state.length === 0 || state.length > MAX_STATE_LENGTH) throw invalidContinuation(); + const [payload, signature, extra] = state.split("."); + if (!payload || !signature || extra !== undefined) throw invalidContinuation(); + const expected = Buffer.from(this.sign(payload), "base64url"); + let received: Buffer; + try { + received = Buffer.from(signature, "base64url"); + } catch { + throw invalidContinuation(); + } + if (received.length !== expected.length || !timingSafeEqual(received, expected)) throw invalidContinuation(); + let decoded: unknown; + try { + decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")); + } catch { + throw invalidContinuation(); + } + if ( + typeof decoded !== "object" || + decoded === null || + Array.isArray(decoded) || + (decoded as { version?: unknown }).version !== 1 || + typeof (decoded as { approvalId?: unknown }).approvalId !== "string" + ) { + throw invalidContinuation(); + } + const approvalId = (decoded as { approvalId: string }).approvalId; + if (!this.records.has(approvalId)) throw invalidContinuation(); + return { approvalId }; + } + + pending(continuation: ApprovalContinuation, binding: ApprovalBinding): ApprovalSummary { + const record = this.records.get(continuation.approvalId); + if (record === undefined) throw invalidContinuation(); + const receivedBinding = this.digestBinding(binding); + if ( + receivedBinding.length !== record.bindingDigest.length || + !timingSafeEqual(receivedBinding, record.bindingDigest) + ) { + throw invalidContinuation(); + } + return record.approval; + } + + complete(continuation: ApprovalContinuation): void { + if (!this.records.delete(continuation.approvalId)) throw invalidContinuation(); + } + + state(continuation: ApprovalContinuation): string { + if (!this.records.has(continuation.approvalId)) throw invalidContinuation(); + const payload = Buffer.from( + JSON.stringify({ version: 1, approvalId: continuation.approvalId }), + "utf8" + ).toString("base64url"); + return `${payload}.${this.sign(payload)}`; + } + + private discardExpired(): void { + const now = Date.now(); + for (const [approvalId, record] of this.records) { + if (Date.parse(record.approval.expiresAt) <= now) this.records.delete(approvalId); + } + } + + private digestBinding(binding: ApprovalBinding): Buffer { + const argumentsForContinuation = { ...binding.arguments }; + if (binding.operation === "profiles/switch" || binding.operation === "profiles/reset") { + // A retry re-captures profile state. The profile manager still enforces the new revision and lock, + // while the continuation remains bound to the same requested action and target profile. + delete argumentsForContinuation.selectionRevision; + } + return createHmac("sha256", this.bindingKey) + .update(canonicalJson({ ...binding, arguments: argumentsForContinuation })) + .digest(); + } + + private sign(payload: string): string { + return createHmac("sha256", this.stateKey).update(payload).digest("base64url"); + } +} diff --git a/src/mcp/server/miftah-server.ts b/src/mcp/server/miftah-server.ts index f3196329..844868d6 100644 --- a/src/mcp/server/miftah-server.ts +++ b/src/mcp/server/miftah-server.ts @@ -1,4 +1,4 @@ -import { Server, ProtocolErrorCode } from "@modelcontextprotocol/server"; +import { inputRequired, inputResponse, Server, ProtocolErrorCode } from "@modelcontextprotocol/server"; import type { CallToolResult, GetPromptRequest, @@ -34,6 +34,11 @@ import { type ApprovalMechanism, type ApprovalSummary } from "../../approvals/approval-store.js"; +import { + ApprovalInputRequiredSignal, + ApprovalContinuationStore, + type ApprovalContinuation +} from "../../approvals/approval-continuation-store.js"; import { SecretRedactor, redactUri } from "../../secrets/redact.js"; import { bindProfileTransitionConfirmationVerifier, @@ -170,7 +175,7 @@ type ResourcePromptProxyAvailability = ResourcePromptProxyAvailable | ResourcePr type ApprovalResolution = | { readonly kind: "consumed" } | { readonly kind: "delegated-agent"; readonly token: string } - | { readonly kind: "form"; readonly token: string }; + | { readonly kind: "form"; readonly state: string }; interface ApprovalErrorFactory { required(binding: ApprovalBinding, token: string): MiftahError; @@ -353,7 +358,8 @@ export class MiftahServer { identityManager?: IdentityManager, private readonly runtimeConfigPath?: string, private readonly modernProfileContext?: ModernProfileContextRuntimeOptions, - private readonly resourceSubscriptionsEnabled = true + private readonly resourceSubscriptionsEnabled = true, + private readonly approvalContinuations = new ApprovalContinuationStore() ) { if ( modernProfileContext !== undefined && @@ -391,6 +397,7 @@ export class MiftahServer { ? { resources: { listChanged: true }, prompts: { listChanged: true } } : {}) }, + requestState: { verify: (state) => this.approvalContinuations.verify(state) }, instructions: [ "Miftah wraps an upstream MCP and routes requests through local credential profiles.", ...(this.resourcePromptProxy.available @@ -499,7 +506,7 @@ export class MiftahServer { }); this.registerHandlers(); this.server.onclose = () => { - void this.close().catch(() => undefined); + void this.close().catch((error: unknown) => this.reportShutdownFailure(error)); }; } @@ -1091,7 +1098,7 @@ export class MiftahServer { args, audit, source, - { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }, + this.approvalRequestContext(ctx), upstreamRequest, prepared.modern ) @@ -1101,7 +1108,7 @@ export class MiftahServer { args, audit, source, - { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }, + this.approvalRequestContext(ctx), upstreamRequest ); }, @@ -1151,7 +1158,7 @@ export class MiftahServer { this.server.setRequestHandler('resources/subscribe', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const approvalContext = this.approvalRequestContext(ctx); const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { @@ -1179,7 +1186,7 @@ export class MiftahServer { this.server.setRequestHandler('resources/unsubscribe', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const approvalContext = this.approvalRequestContext(ctx); const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { @@ -1241,7 +1248,7 @@ export class MiftahServer { this.server.setRequestHandler('resources/read', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const approvalContext = this.approvalRequestContext(ctx); const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { @@ -1303,7 +1310,7 @@ export class MiftahServer { this.server.setRequestHandler('prompts/get', async (request, ctx) => { const auditSource = await this.requestAuditFallbackProfileState(); - const approvalContext: ApprovalRequestContext = { requestId: ctx.mcpReq.id, signal: ctx.mcpReq.signal }; + const approvalContext = this.approvalRequestContext(ctx); const upstreamRequest = this.upstreamRequestContext(ctx); return this.runAudited( { @@ -1366,6 +1373,14 @@ export class MiftahServer { }; } + private approvalRequestContext(extra: ProxiedRequestExtra): ApprovalRequestContext { + return { + signal: extra.mcpReq.signal, + ...(extra.mcpReq.inputResponses === undefined ? {} : { inputResponses: extra.mcpReq.inputResponses }), + requestState: extra.mcpReq.requestState + }; + } + private async runWithUpstreamRequest( upstreamRequest: UpstreamRequestContext | undefined, operation: () => Promise @@ -2049,6 +2064,11 @@ export class MiftahServer { ): Promise { const supportsFormElicitation = context !== undefined && this.server.getClientCapabilities()?.elicitation?.form !== undefined; + const continuation = context?.requestState(); + if (continuation !== undefined) { + if (!supportsFormElicitation || context === undefined) throw errors.unavailable(binding); + return this.finishFormApproval(binding, context, continuation, errors); + } const approvalMechanism: ApprovalMechanism = supportsFormElicitation ? "form" : "delegated-agent"; if (!supportsFormElicitation && !this.delegatedAgentApprovalEnabled()) { await this.enqueueApprovalTransition(async () => { @@ -2084,82 +2104,97 @@ export class MiftahServer { ), (value) => this.approvals.revoke(value.approval.id) ); + let state: string | undefined; + if (supportsFormElicitation) { + try { + state = this.approvalContinuations.mint(binding, requested.approval); + } catch (error) { + this.approvals.revoke(requested.approval.id); + throw error; + } + } if (requested.created) { try { await this.writeApproval("requested", requested.approval); } catch (error) { this.approvals.revoke(requested.approval.id); + if (state !== undefined) { + this.approvalContinuations.complete({ approvalId: requested.approval.id }); + } throw error; } } - return supportsFormElicitation - ? { kind: "form", token: requested.token } + return supportsFormElicitation && state !== undefined + ? { kind: "form", state } : { kind: "delegated-agent", token: requested.token }; }); if (resolution.kind === "consumed") return; if (resolution.kind === "delegated-agent") { throw errors.required(binding, resolution.token); } - if (context === undefined) throw new Error("Form approval requires an MCP request context."); - let result; - try { - result = await this.server.elicitInput( - { - mode: "form", - message: "Approve this exact operation?", - requestedSchema: { - type: "object", - properties: { approved: { type: "boolean" } }, - required: ["approved"] - } - }, - { relatedRequestId: context.requestId, signal: context.signal, timeout: 60_000 } - ); - } catch { - await this.finalizeNativeApproval(resolution.token, binding, false); - throw errors.notAccepted(binding); - } - if (result.action === "accept" && result.content?.approved === true) { - await this.finalizeNativeApproval(resolution.token, binding, true); - return; - } - await this.finalizeNativeApproval(resolution.token, binding, false); - throw errors.notAccepted(binding); + throw this.formApprovalRequired(resolution.state, errors.notAccepted(binding).code); } - private async finalizeNativeApproval(token: string, binding: ApprovalBinding, accepted: boolean): Promise { + private async finishFormApproval( + binding: ApprovalBinding, + context: ApprovalRequestContext, + continuation: ApprovalContinuation, + errors: ApprovalErrorFactory + ): Promise { + const approval = this.approvalContinuations.pending(continuation, binding); + const response = inputResponse(context.inputResponses, "approval"); + if (response.kind !== "elicit") { + throw this.formApprovalRequired( + this.approvalContinuations.state(continuation), + errors.notAccepted(binding).code + ); + } + const expired = Date.parse(approval.expiresAt) <= Date.now(); + const accepted = !expired && response.action === "accept" && response.content?.approved === true; await this.enqueueApprovalTransition(async () => { - await this.expireApprovals(); - if (accepted) { - const approval = await this.withApprovalExpiryAudit( - () => this.approvals.approveAndConsume(token, binding), - (value) => this.approvals.revoke(value.id) - ); - try { - await this.writeApproval("approved", approval); - await this.writeApproval("consumed", approval); - } catch (error) { - this.approvals.revoke(approval.id); - throw error; + const expiredApprovals = await this.expireApprovals(); + this.approvalContinuations.complete(continuation); + this.approvals.revoke(approval.id); + if (expired) { + if (!expiredApprovals.some((candidate) => candidate.id === approval.id)) { + await this.writeApproval("expired", approval); } - return; + throw new MiftahError("APPROVAL_EXPIRED", "APPROVAL_EXPIRED: approval token has expired"); } - const approval = await this.withApprovalExpiryAudit( - () => this.approvals.deny(token), - (value) => this.approvals.revoke(value.id) - ); - try { - await this.writeApproval("denied", approval); - } catch (error) { - this.approvals.revoke(approval.id); - throw error; + if (accepted) { + await this.writeApproval("approved", approval); + await this.writeApproval("consumed", approval); + return; } + await this.writeApproval("denied", approval); }); + if (!accepted) throw errors.notAccepted(binding); + } + + private formApprovalRequired(state: string, errorCode: MiftahError["code"]): ApprovalInputRequiredSignal { + return new ApprovalInputRequiredSignal( + inputRequired({ + inputRequests: { + approval: inputRequired.elicit({ + mode: "form", + message: "Approve this exact operation?", + requestedSchema: { + type: "object", + properties: { approved: { type: "boolean" } }, + required: ["approved"] + } + }) + }, + requestState: state + }), + errorCode + ); } - private async expireApprovals(): Promise { - this.approvals.expire(); + private async expireApprovals(): Promise { + const expired = this.approvals.expire(); await this.writeExpiredApprovalTransitions(); + return expired; } private async withApprovalExpiryAudit( @@ -3013,6 +3048,16 @@ export class MiftahServer { await audit.finish(resultAudit?.(result) ?? { status: "success" }); return this.redactor.redact(result); } catch (error) { + if (error instanceof ApprovalInputRequiredSignal) { + if (!audit.isFinalized) { + try { + await audit.finish({ status: "confirmation-required", errorCode: error.errorCode }); + } catch (auditError) { + throw this.toSafeError(auditError); + } + } + return error.result as Result; + } let safeError = this.toSafeError(error); if (!audit.isFinalized) { try { @@ -3349,6 +3394,11 @@ export class MiftahServer { const safeError = this.toSafeError(error); process.emitWarning(safeError.message, { code: "MIFTAH_RESOURCE_SUBSCRIPTION_CLEANUP_FAILED" }); } + + private reportShutdownFailure(error: unknown): void { + const safeError = this.toSafeError(error); + process.emitWarning(safeError.message, { code: "MIFTAH_SHUTDOWN_FAILED" }); + } } function extractProfileContext( diff --git a/src/mcp/server/operation-pipeline.ts b/src/mcp/server/operation-pipeline.ts index 5c23f046..efacdac4 100644 --- a/src/mcp/server/operation-pipeline.ts +++ b/src/mcp/server/operation-pipeline.ts @@ -1,5 +1,6 @@ import type { AuditScope } from "../../audit/audit-trail.js"; import type { ApprovalBinding } from "../../approvals/approval-store.js"; +import { ApprovalInputRequiredSignal } from "../../approvals/approval-continuation-store.js"; import { IdentityManager } from "../../identity/identity-manager.js"; import { PolicyEngine } from "../../policy/policy-engine.js"; import type { PolicyDecision } from "../../policy/policy-types.js"; @@ -27,8 +28,9 @@ export type CapturedProfileState = Pick< > & { readonly profileContextCorrelation?: string }; export interface ApprovalRequestContext { - readonly requestId: string | number; readonly signal: AbortSignal; + readonly inputResponses?: Record; + readonly requestState: () => State | undefined; } export interface ResolvedOperation { @@ -211,6 +213,7 @@ export class OperationPipeline { await this.assertProfileSelectionAllows(operation, profile, profileConfig.lease, decision.risk); return this.options.redactor.redact(target.redact(await target.execute(session, operation.upstreamRequestOptions))); } catch (error) { + if (error instanceof ApprovalInputRequiredSignal) throw error; const safeError = this.toSafeError(error); const matcherEvidence = matcherEvidenceFromError(safeError); if (matcherEvidence !== undefined) { diff --git a/src/runtime/create-miftah-runtime.ts b/src/runtime/create-miftah-runtime.ts index 43d5b911..4191594a 100644 --- a/src/runtime/create-miftah-runtime.ts +++ b/src/runtime/create-miftah-runtime.ts @@ -1,4 +1,5 @@ import type { McpServerFactory, Transport } from "@modelcontextprotocol/server"; +import { ApprovalContinuationStore } from "../approvals/approval-continuation-store.js"; import { resolvePath } from "../config/path-resolve.js"; import type { MiftahConfig } from "../config/types.js"; import { MiftahServer } from "../mcp/server/miftah-server.js"; @@ -24,6 +25,7 @@ export interface MiftahRuntimeOptions { interface MiftahRuntimeFactoryOptions extends MiftahRuntimeOptions { readonly profileState?: { readonly persistActiveProfile?: false; readonly scope?: "process" | "session" }; readonly resourceSubscriptionsEnabled?: boolean; + readonly approvalContinuations?: ApprovalContinuationStore; } async function createConfiguredMiftahServer( @@ -50,7 +52,8 @@ async function createConfiguredMiftahServer( runtime.identities, runtimeConfigPath, options.modernProfileContext, - options.resourceSubscriptionsEnabled + options.resourceSubscriptionsEnabled, + options.approvalContinuations ); return { config: runtime.config, server }; @@ -72,8 +75,16 @@ function configuredMiftahServerFactory( configPath: string, options: MiftahRuntimeFactoryOptions ): McpServerFactory { - return async () => { - const configured = await createConfiguredMiftahServer(configPath, options); + const approvalContinuations = new ApprovalContinuationStore(); + return async (context) => { + const eraOptions: MiftahRuntimeFactoryOptions = context.era === "modern" + ? { ...options, resourceSubscriptionsEnabled: false, approvalContinuations } + : { + ...(options.profileState === undefined ? {} : { profileState: options.profileState }), + resourceSubscriptionsEnabled: true, + approvalContinuations + }; + const configured = await createConfiguredMiftahServer(configPath, eraOptions); try { return await configured.server.prepareForServing(); } catch (error) { diff --git a/tests/approval-continuation-store.test.ts b/tests/approval-continuation-store.test.ts new file mode 100644 index 00000000..4c50af08 --- /dev/null +++ b/tests/approval-continuation-store.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; +import { ApprovalContinuationStore } from "../src/approvals/approval-continuation-store.js"; +import type { ApprovalBinding, ApprovalSummary } from "../src/approvals/approval-store.js"; + +function binding(argumentsValue: Record = { name: "first" }): ApprovalBinding { + return { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: argumentsValue + }; +} + +function approval(id: string, expiresAt = "2999-01-01T00:00:00.000Z"): ApprovalSummary { + return { + id, + status: "pending", + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + mechanism: "form", + expiresAt + }; +} + +describe("approval continuation store", () => { + it("integrity-binds one pending continuation to the exact operation", () => { + const store = new ApprovalContinuationStore(); + const original = binding({ nested: { second: 2, first: 1 }, name: "first" }); + const state = store.mint(original, approval("approval-1")); + const continuation = store.verify(state); + + expect(store.pending(continuation, binding({ name: "first", nested: { first: 1, second: 2 } }))).toMatchObject({ + id: "approval-1", + mechanism: "form" + }); + expect(() => store.pending(continuation, binding({ name: "changed" }))).toThrow("APPROVAL_INVALID"); + const changedLastCharacter = state.endsWith("A") ? "B" : "A"; + expect(() => store.verify(`${state.slice(0, -1)}${changedLastCharacter}`)).toThrow("APPROVAL_INVALID"); + + store.complete(continuation); + expect(() => store.verify(state)).toThrow("APPROVAL_INVALID"); + expect(() => store.complete(continuation)).toThrow("APPROVAL_INVALID"); + }); + + it("keeps profile-transition approval stable while the independently enforced revision changes", () => { + const store = new ApprovalContinuationStore(); + const first: ApprovalBinding = { + ...binding({ profile: "personal", selectionRevision: 1 }), + profile: "personal", + upstream: "profiles", + operation: "profiles/switch", + name: "personal", + displayName: "profile 'personal'" + }; + const state = store.mint(first, { ...approval("approval-2"), profile: "personal", operation: "profiles/switch" }); + const continuation = store.verify(state); + + expect(store.pending(continuation, { + ...first, + arguments: { profile: "personal", selectionRevision: 2 } + }).id).toBe("approval-2"); + }); + + it("bounds pending state and discards expired entries before admitting a replacement", () => { + expect(() => new ApprovalContinuationStore(0)).toThrow("positive integer"); + const store = new ApprovalContinuationStore(1); + const expiredState = store.mint(binding(), approval("expired", "2000-01-01T00:00:00.000Z")); + const currentState = store.mint(binding(), approval("current")); + + expect(() => store.verify(expiredState)).toThrow("APPROVAL_INVALID"); + expect(store.verify(currentState)).toEqual({ approvalId: "current" }); + expect(() => store.mint(binding(), approval("overflow"))).toThrow("APPROVAL_LIMIT_EXCEEDED"); + }); + + it.each(["", "not-a-state", "e30.invalid", `${"a".repeat(513)}.value`])( + "rejects malformed state %j", + (state) => { + const store = new ApprovalContinuationStore(); + expect(() => store.verify(state)).toThrow("APPROVAL_INVALID"); + } + ); + + it("reissues the exact signed state for a still-pending continuation", () => { + const store = new ApprovalContinuationStore(); + const valid = store.mint(binding(), approval("approval-3")); + const continuation = store.verify(valid); + expect(store.state(continuation)).toBe(valid); + }); +}); diff --git a/tests/mcp-v2-serving.test.ts b/tests/mcp-v2-serving.test.ts index 51e92de8..40b4eea2 100644 --- a/tests/mcp-v2-serving.test.ts +++ b/tests/mcp-v2-serving.test.ts @@ -1,4 +1,4 @@ -import { access, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; @@ -79,6 +79,71 @@ describe("MCP SDK v2 serving interoperability", () => { } }); + it("continues a modern HTTP form approval across request-scoped server instances", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-v2-approval-")); + temporaryDirectories.push(directory); + const path = join(directory, "miftah.json"); + const auditPath = join(directory, "audit.jsonl"); + const createCountPath = join(directory, "create-count"); + const secretArgument = "modern-approval-secret"; + await writeFile( + path, + JSON.stringify({ + version: "1", + name: "v2-approval-test", + defaultProfile: "work", + upstream: { + transport: "stdio", + command: process.execPath, + args: [fixture] + }, + profiles: { + work: { + policy: "confirm", + env: { TEST_CREATE_ITEM_COUNT_PATH: createCountPath } + } + }, + policies: { confirm: { requireConfirmation: ["create_item"] } }, + audit: { path: auditPath }, + server: { http: { port: 0, maxSessions: 4, sessionIdleTimeoutMs: 1_000 } } + }) + ); + const server = await startMiftahHttpServer(path); + httpServers.push(server); + const transport = new StreamableHTTPClientTransport(server.url); + const client = new Client( + { name: "miftah-modern-approval-test", version: "1.0.0" }, + { + versionNegotiation: { mode: "auto" }, + capabilities: { elicitation: { form: {} } } + } + ); + const elicitationRequests: unknown[] = []; + client.setRequestHandler('elicitation/create', async (request) => { + elicitationRequests.push(request); + return { action: "accept", content: { approved: true } }; + }); + + try { + await client.connect(transport); + expect(await client.callTool({ name: "create_item", arguments: { name: secretArgument } })).toMatchObject({ + content: [{ type: "text", text: `created:${secretArgument}` }] + }); + expect(elicitationRequests).toHaveLength(1); + expect(JSON.stringify(elicitationRequests)).not.toContain(secretArgument); + expect(await readFile(createCountPath, "utf8")).toBe("1\n"); + const approvalActions = (await readFile(auditPath, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((event) => event.kind === "approval") + .map((event) => event.approvalAction); + expect(approvalActions).toEqual(["requested", "approved", "consumed"]); + } finally { + await client.close(); + } + }); + it("does not probe or advertise connection-bound resource subscriptions for modern HTTP requests", async () => { const directory = await mkdtemp(join(tmpdir(), "miftah-v2-serving-probe-")); temporaryDirectories.push(directory); @@ -127,7 +192,7 @@ describe("MCP SDK v2 serving interoperability", () => { ["modern", { versionNegotiation: { mode: "auto" as const } }, "modern"], ["legacy", undefined, "legacy"] ])("serves %s clients through the SDK v2 stdio entry", async (_era, clientOptions, expectedEra) => { - const path = await configPath(); + const path = await configPath({ env: { TEST_RESOURCE_SUBSCRIPTIONS: "true" } }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const baseFactory = createMiftahServerFactory(path); const eras: string[] = []; @@ -143,6 +208,11 @@ describe("MCP SDK v2 serving interoperability", () => { try { await client.connect(clientTransport); expect([...new Set(eras)]).toEqual([expectedEra]); + if (expectedEra === "legacy") { + expect(client.getServerCapabilities()?.resources?.subscribe).toBe(true); + } else { + expect(client.getServerCapabilities()?.resources?.subscribe).not.toBe(true); + } expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("whoami"); } finally { await client.close(); diff --git a/tests/mcp-wrapper.test.ts b/tests/mcp-wrapper.test.ts index c2d35ebf..b0705b8c 100644 --- a/tests/mcp-wrapper.test.ts +++ b/tests/mcp-wrapper.test.ts @@ -3400,6 +3400,32 @@ describe("Miftah MCP wrapper", () => { } }); + it("reports a sanitized shutdown failure triggered by transport close", async () => { + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: {} } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const close = vi.spyOn(wrapper, "close").mockRejectedValueOnce(new Error("private shutdown detail")); + const emitWarning = vi.spyOn(process, "emitWarning").mockImplementation(() => undefined); + + try { + wrapper.server.onclose?.(); + await expect.poll(() => emitWarning.mock.calls.length).toBe(1); + expect(emitWarning).toHaveBeenCalledWith("UPSTREAM_CALL_FAILED: private shutdown detail", { + code: "MIFTAH_SHUTDOWN_FAILED" + }); + } finally { + close.mockRestore(); + emitWarning.mockRestore(); + await wrapper.close(); + } + }); + it("bounds resource subscription cleanup while switching profiles", async () => { const directory = await mkdtemp(join(tmpdir(), "miftah-resource-subscription-cleanup-")); const unsubscribeCountPath = join(directory, "unsubscribe-count");